fastest-validator
fastest-validator copied to clipboard
Failing to compile schema with enum values containing double-quotes
const schema = {
"technology.screen_size": {
"type": "array",
"items": {
"type": "enum",
"values": [
"",
"Under 20\"",
"20-29\"",
"30-39\"",
"40-49\"",
"50-59\"",
"60-69\"",
"70-80\"",
"Over 80\""
]
},
"optional": true
}
}
const Validator = require("fastest-validator");
const v = new Validator();
const check = v.compile(schema);
Stacktrace
➜ releaseit-backend git:(main) ✗ node test.js
undefined:5
errors.push({ type: "enumValue", message: "The '{field}' field value '{expected}' does not match any of the allowed values.", field: field, expected: ", Under 20", 20-29", 30-39", 40-49", 50-59", 60-69", 70-80", Over 80"", actual: value });
^
SyntaxError: Unexpected token '-'
at new Function (<anonymous>)
at Validator.compileRule (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/validator.js:284:15)
at Validator.module.exports (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/rules/array.js:88:17)
at Validator.compileRule (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/validator.js:281:34)
at Validator.module.exports (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/rules/object.js:67:25)
at Validator.compileRule (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/validator.js:281:34)
at Validator.compile (/Users/ashneilroy/Desktop/dev/releaseit-backend/node_modules/fastest-validator/lib/validator.js:206:24)
at Object.<anonymous> (/Users/ashneilroy/Desktop/dev/releaseit-backend/test.js:25:17)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
There seems to be an issue compiling schemas with enum values with the double-quote (") symbol
Am on [email protected] Let me know if you need any more information
in https://github.com/icebob/fastest-validator/blob/master/lib/rules/enum.js
module.exports = function({ schema, messages }, path, context) {
const enumStr = JSON.stringify(schema.values || []);
return {
source: `
if (${enumStr}.indexOf(value) === -1)
${this.makeError({ type: "enumValue", expected: "\"" + schema.values.map(v => v.replace(/"/g, '\\"')).join(", ") + "\"", actual: "value", messages })}
return value;
`
};
};
This escapes any double-quotes provided in values
Great, please create a PR.