gpt4 book ai didi

javascript - 如何使用带有 Ajv 的正则表达式验证字符串?

转载 作者:行者123 更新时间:2023-12-04 11:22:32 26 4
gpt4 key购买 nike

我正在尝试使用此正则表达式 ^+[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/(打开控制台/调试器以查看完整错误)

最佳答案

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) }


相关
  • Why do linters pick on useless escape character?
  • 关于javascript - 如何使用带有 Ajv 的正则表达式验证字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62219186/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com