如何使用 Ajv 的正则表达式验证字符串?
How do I validate a string using a regular expression with Ajv?
我正在尝试使用此正则表达式验证字符串(Phone 数字)^+[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!');
}
Link 到 JSFiddle:http://jsfiddle.net/xnw2b9zL/4/(打开控制台/调试器以查看完整错误)
除了@customcommander评论。
关于 format 的文档指出:
regex: tests whether a string is a valid regular expression by passing
it to RegExp constructor.
在 javascript 中,当您声明一个字符串时,反斜杠将被解释。这就是为什么你需要加倍反斜杠。
如果不这样做,则传递给 Avg 并最终传递给 new RegExp(...)
的是字符串 "^+[0-9]{9,12}$"
,这是一个不正确的正则表达式。
PS: 好狗
TL;博士
您的正则表达式 在文字符号形式中有效,但在嵌入字符串的构造函数形式中无效。
"\+"
❌"\+"
✅
将正则表达式嵌入字符串时,仔细检查转义字符!
为什么?
因为无用的转义字符将被忽略。如果不是为了构建正则表达式,你没有理由转义 '+'
字符:
"\+" === "+"
//=> true
您看到的错误与数据无关,是在架构的构建中。正如您在这里看到的:
const ajv = new Ajv;
try {
ajv.compile({type: 'string' , pattern: '^\+[0-9]{9,12}$'});
} catch (e) {
console.log(`ERR! ${e.message}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js"></script>
但深入挖掘,也与Ajv无关。 Ajv 确实提到:
Ajv uses new RegExp(value) to create the regular expression that will be used to test data.
见https://ajv.js.org/keywords.html#pattern
那么 new RegExp("\+")
是什么意思?让我们找出答案:
// similar error because "\+" and "+" are the same string
try { new RegExp("\+") } catch (e) { console.log(e.message) }
try { new RegExp("+") } catch (e) { console.log(e.message) }
相关
我正在尝试使用此正则表达式验证字符串(Phone 数字)^+[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!');
}
Link 到 JSFiddle:http://jsfiddle.net/xnw2b9zL/4/(打开控制台/调试器以查看完整错误)
除了@customcommander评论。
关于 format 的文档指出:
regex: tests whether a string is a valid regular expression by passing it to RegExp constructor.
在 javascript 中,当您声明一个字符串时,反斜杠将被解释。这就是为什么你需要加倍反斜杠。
如果不这样做,则传递给 Avg 并最终传递给 new RegExp(...)
的是字符串 "^+[0-9]{9,12}$"
,这是一个不正确的正则表达式。
PS: 好狗
TL;博士
您的正则表达式 在文字符号形式中有效,但在嵌入字符串的构造函数形式中无效。
"\+"
❌"\+"
✅
将正则表达式嵌入字符串时,仔细检查转义字符!
为什么?
因为无用的转义字符将被忽略。如果不是为了构建正则表达式,你没有理由转义 '+'
字符:
"\+" === "+"
//=> true
您看到的错误与数据无关,是在架构的构建中。正如您在这里看到的:
const ajv = new Ajv;
try {
ajv.compile({type: 'string' , pattern: '^\+[0-9]{9,12}$'});
} catch (e) {
console.log(`ERR! ${e.message}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js"></script>
但深入挖掘,也与Ajv无关。 Ajv 确实提到:
Ajv uses new RegExp(value) to create the regular expression that will be used to test data.
见https://ajv.js.org/keywords.html#pattern
那么 new RegExp("\+")
是什么意思?让我们找出答案:
// similar error because "\+" and "+" are the same string
try { new RegExp("\+") } catch (e) { console.log(e.message) }
try { new RegExp("+") } catch (e) { console.log(e.message) }
相关