【发布时间】:2020-09-24 21:17:36
【问题描述】:
我正在尝试使用此正则表达式验证字符串(电话号码)^+[0-9]{9,12}$
但我收到此错误
... .pattern should match format "regex" ...
我浏览了https://ajv.js.org 等处的文档。查看了示例等并尝试了很多变体,但似乎无法弄清楚我的代码有什么问题。
这是我的代码:
const schema = {
type: 'object',
properties: {
users: {
type: 'array',
items: {
type: 'object',
properties: {
userReference: { type: 'string' },
phone: {
type: 'string'
, pattern: "^\+[0-9]{9,12}$" // If I remove this line, the model is seen as valid (and no errors)
}
}
}
}
},
required: ['users'],
errorMessage: { _: "One or more of the fields in the 'legacy' data path are incorrect." }
};
const schemaSample = {
"users": [
{
"phone": "+25512345678", // should be valid
"userReference": "AAA"
},
{
"phone": "+5255 abc 12345678", // should be invalid
"userReference": "BBB"
}
]
};
var ajv = Ajv();
ajv.addSchema(schema, 'schema');
var valid = ajv.validate('schema', schemaSample);
if (valid) {
console.log('Model is valid!');
} else {
console.log('Model is invalid!');
}
链接到 JSFiddle:http://jsfiddle.net/xnw2b9zL/4/(打开控制台/调试器查看完整错误)
【问题讨论】:
-
你很可能忘记了双重转义:
"\+"应该是"\\+" -
我真的在这该死的东西上花了好几个小时!!谢谢那成功了。如果您将其发布为答案,我会将其标记为正确,否则我将稍后回答我自己的问题。
标签: javascript jsonschema ajv