简体   繁体   English

正则表达式-信用卡验证

[英]Regex - Credit Card validation

I'm looking for a way to validate the beginning of a credit card pattern. 我正在寻找一种验证信用卡模式开始的方法。 So for example, let's take MasterCard. 因此,以万事达卡为例。

It says that (ref: https://www.regular-expressions.info/creditcard.html ): 它说(ref: https : //www.regular-expressions.info/creditcard.html ):

MasterCard numbers either start with the numbers 51 through 55... 万事达卡号码以51到55开头。

I'm looking for a regex that returns true when the user enters: 我正在寻找当用户输入时返回true的正则表达式:

 const regex = /^5|5[1-5]/; // this is not working :( regex.test("5"); // true regex.test("51"); // true regex.test("55"); // true regex.test("50"); // should be false, but return true because it matches the `5` at the beginning :( 

It should be: 它应该是:

const regex = /^5[1-5]/;

Your regex matches either a string beginning with 5 or a string that has 51 through 55 anywhere in it, because the ^ is only on the left side of the | 您的正则表达式匹配以5开头的字符串或其中以5155开头的字符串,因为^仅位于|的左侧| .

If you want to allow a partial entry, you can use: 如果要允许部分输入,可以使用:

const regex = /^5(?:$|[1-5])/;

See Validating credit card format using regular expressions? 请参阅使用正则表达式验证信用卡格式? for a regular expression that matches most popular cards. 匹配最流行卡片的正则表达式。

Are you validating as the user types in? 您是否在用户输入时进行验证? If so, you could add an end of line ($) to the first option, so that it returns true only if: 如果是这样,则可以在第一个选项中添加行尾($),以便仅在以下情况下返回true:

  • 5 is the only character typed so far 到目前为止,唯一输入的字符是5
  • The string begins with 50-55 字符串以50-55开头

const regex = /^(5$|5[1-5])/;

regex.test("5"); // true
regex.test("51"); // true
regex.test("55"); // true
regex.test("50"); // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM