信用卡regex在AngularJs中不工作。

时间:2022-11-17 19:43:00

I am using the following regex to validate the credit card number for various credit card types:

我正在使用下面的regex验证各种信用卡类型的信用卡号:

/^((5[1-5]\d{14})|(4\d{12}(\d{3})?)|(3[47]\d{13})|(6011\d{14})|((30[0-5]|36\d|38\d)\d{11}))(?<=\d)$/

/ ^((5[1 - 5]\ d { 14 })|(4 \ d { 12 }(\ d { 3 })?)|(3[47]\ d { 13 })|(6011 \ d { 14 })|(36 \ d(30(0 - 5)| | 38 \ d)\ d { 11 }))(? < = \ d)/美元

This works as expected using online validators such as regex101.com but as soon as I am trying to use it with ngPattern it does not validate as expected. Basically, it allows to enter characters as well even though the regex would not allow that.

使用regex101.com这样的在线验证器可以正常工作,但是当我尝试在ngPattern中使用它时,它并不像预期的那样有效。基本上,即使regex不允许输入字符,它也允许输入字符。

Sample: http://plnkr.co/edit/r6qGoyfKHnzoOQmv0kpv

示例:http://plnkr.co/edit/r6qGoyfKHnzoOQmv0kpv

<input type="text" name='cc' ng-model="usd" ng-pattern="/^(5[1-5]\d{14})|(4\d{12}(\d{3})?)|(3[47]\d{13})|(6011\d{14})|((30[0-5]|36\d|38\d)\d{11})$/" 
   placeholder="credit card number"/>

Try enter the Visa test card number with some characters at the end.

尝试在最后输入带有一些字符的签证测试卡号码。

Any help on this appreciated.

对此有任何帮助。

1 个解决方案

#1


2  

You need to put everything into a group:

你需要把所有东西都放到一个组中:

^(?:(5[1-5]\d{14})|(4\d{12}(\d{3})?)|(3[47]\d{13})|(6011\d{14})|((30[0-5]|36\d|38\d)\d{11}))$
 ^^^                                                                                       ^

See the regex demo

看到regex演示

The problem arose because the ^ and $ anchors only applied to the first and last alternatives respectively.

问题是因为^和$锚分别只适用于第一个和最后一个选择。

Adding the outer group (it can be capturing or non-capturing, in AngularJS it does not matter much) will make sure the start and end anchors will be applied to the whole regex pattern.

添加外部组(它可以捕获或非捕获,在AngularJS中没有多大关系)将确保开始和结束锚将应用于整个regex模式。

#1


2  

You need to put everything into a group:

你需要把所有东西都放到一个组中:

^(?:(5[1-5]\d{14})|(4\d{12}(\d{3})?)|(3[47]\d{13})|(6011\d{14})|((30[0-5]|36\d|38\d)\d{11}))$
 ^^^                                                                                       ^

See the regex demo

看到regex演示

The problem arose because the ^ and $ anchors only applied to the first and last alternatives respectively.

问题是因为^和$锚分别只适用于第一个和最后一个选择。

Adding the outer group (it can be capturing or non-capturing, in AngularJS it does not matter much) will make sure the start and end anchors will be applied to the whole regex pattern.

添加外部组(它可以捕获或非捕获,在AngularJS中没有多大关系)将确保开始和结束锚将应用于整个regex模式。