Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ function buildInnerObject (context, location) {

for (const key of requiredProperties) {
if (!propertiesKeys.includes(key)) {
code += `if (obj['${key}'] === undefined) throw new Error('"${key}" is required!')\n`
const sanitizedKey = JSON.stringify(key)
code += `if (obj[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n`
}
}

Expand Down Expand Up @@ -387,7 +388,7 @@ function buildInnerObject (context, location) {
`
} else if (isRequired) {
code += ` else {
throw new Error('${sanitizedKey} is required!')
throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')
}
`
} else {
Expand Down
68 changes: 68 additions & 0 deletions test/sanitize7.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'use strict'

const test = require('tap').test
const build = require('..')

test('required property containing single quote, contains property', (t) => {
t.plan(1)

const stringify = build({
type: 'object',
properties: {
'\'': { type: 'string' }
},
required: [
'\''
]
})

t.throws(() => stringify({}), new Error('"\'" is required!'))
})

test('required property containing double quote, contains property', (t) => {
t.plan(1)

const stringify = build({
type: 'object',
properties: {
'"': { type: 'string' }
},
required: [
'"'
]
})

t.throws(() => stringify({}), new Error('""" is required!'))
})

test('required property containing single quote, does not contain property', (t) => {
t.plan(1)

const stringify = build({
type: 'object',
properties: {
a: { type: 'string' }
},
required: [
'\''
]
})

t.throws(() => stringify({}), new Error('"\'" is required!'))
})

test('required property containing double quote, does not contain property', (t) => {
t.plan(1)

const stringify = build({
type: 'object',
properties: {
a: { type: 'string' }
},
required: [
'"'
]
})

t.throws(() => stringify({}), new Error('""" is required!'))
})