javascript 如何使用正则表达式和Ajv验证字符串?

kx7yvsdv  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(130)

我正在尝试使用以下正则表达式验证字符串(电话号码)^+[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/(打开控制台/调试器以查看完整错误)

xhv8bpkk

xhv8bpkk1#

TL; DR

你的正则表达式 is 在文字符号形式中有效,但在嵌入到字符串中的构造函数形式中无效。
"\+""\\+"
当将正则表达式嵌入到字符串中时,请仔细检查转义字符!
为什么
因为无用的转义字符将被忽略。如果不是为了构造正则表达式,你没有理由转义'+'字符:

"\+" === "+"
//=> 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确实提到:
April使用新的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) }

相关

eimct9ow

eimct9ow2#

正则表达式的字符串化错误。为了避免错误,您可以使用native Regex,如下所示:

{
  type: 'string', 
  pattern: /^\+[0-9]{9,12}$/.toString().slice(1, -1)
}

注意,.slice(1, -1)删除了第一个和最后一个字符,它们是regexp分隔符,不应该包含在RegExp构造函数中。

/test/.toString() // "/test/"
/test/.toString().slice(1, -1) // "test"
new RegExp(/test/.toString().slice(1, -1)) // /test/

您也不能使用任何标志,因为它们必须作为RegExp构造函数的单独参数提供。

vs91vp4v

vs91vp4v3#

除了@customcommander评论。
有关格式的文档指出:
regex:通过将字符串传递给RegExp构造函数来测试字符串是否是有效的正则表达式。
在JavaScript中,当你声明一个字符串时,反斜杠会被解释。这就是为什么你需要双反斜线。
如果不这样做,那么传递给Avg和new RegExp(...)的是字符串"^+[0-9]{9,12}$",这是一个不正确的RegExp。

PS:可爱的狗狗

相关问题