使用 val().match() 方法的 Javascript 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8606117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:41:00  来源:igfitidea点击:

Javascript regexp using val().match() method

javascriptjquery

提问by alexistkd

I'm trying to validate a field named phone_number with this rules:

我正在尝试使用以下规则验证名为 phone_number 的字段:

the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874

第一个数字应该是 3 然后是另外 9 个数字,所以总共 10 个数字示例:3216549874

or can be 7 numbers 1234567

或者可以是 7 个数字 1234567

here i have my code:

在这里我有我的代码:

        if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
            missing = true;

Why doesnt work :( when i put that into an online regexp checker shows good.

为什么不起作用:(当我将其放入在线正则表达式检查器时显示良好。

采纳答案by alessioalex

You should be using test instead of match and here's the proper code:

您应该使用 test 而不是 match,这是正确的代码:

.test(/^(3\d{9}|\d{7})$/)

Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).

Match 会找到所有出现的情况,而 test 只会检查是否至少有一个可用(从而验证您的号码)。

回答by Alfabravo

Don't get confused by pipe. Must end each expression

不要被管道混淆。必须结束每个表达式

if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
            missing = true;

http://jsfiddle.net/alfabravoteam/e6jKs/

http://jsfiddle.net/alfabravoteam/e6jKs/

回答by m?ks?

I had similar problem and my solution was to write it like:

我有类似的问题,我的解决方案是这样写:

if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
    missing = true;
}

回答by Kevin B

Try this, it's a little more strict.

试试这个,它更严格一点。

.match(/^(3\d{9}|\d{7})$/)