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

Leg*_*Dev 6 javascript jsonschema ajv

我正在尝试使用此正则表达式^+[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!');
}

Run Code Online (Sandbox Code Playgroud)

链接到 JSFiddle:http : //jsfiddle.net/xnw2b9zL/4/(打开控制台/调试器查看完整错误)

cus*_*der 6

TL; DR

正则表达式一个文字符号的形式有效,但不是在它被嵌入到一个字符串构造函数形式。

"\+"? "\\+"?

将正则表达式嵌入字符串时,请仔细检查您的转义字符!

为什么?

因为无用的转义字符将被忽略。如果不是为了构建正则表达式,您就没有理由转义'+'字符:

"\+" === "+"
//=> true
Run Code Online (Sandbox Code Playgroud)

您看到的错误与数据无关,而是在架构的构建中。正如你在这里看到的:

const ajv = new Ajv;

try {
  ajv.compile({type: 'string' , pattern: '^\+[0-9]{9,12}$'});
} catch (e) {
  console.log(`ERR! ${e.message}`);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

但深入挖掘,它也与 Ajv 无关。Ajv 确实提到:

Ajv 使用 new RegExp(value) 创建将用于测试数据的正则表达式。

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) }
Run Code Online (Sandbox Code Playgroud)

有关的