正则表达式 - 信用卡验证

时间:2018-03-07 17:56:54

标签: javascript regex credit-card

我正在寻找一种方法来验证信用卡模式的开头。例如,让我们拿MasterCard。

它说(参考:https://www.regular-expressions.info/creditcard.html):

  

万事达卡号码以数字51至55开头......

我正在寻找一个在用户输入时返回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 :(




2 个答案:

答案 0 :(得分:0)

应该是:

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

您的正则表达式匹配以5开头的字符串或其中任意位置5155的字符串,因为^仅位于左侧|

如果您想允许部分输入,可以使用:

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

请参阅Validating credit card format using regular expressions?以获取与大多数常用卡相匹配的正则表达式。

答案 1 :(得分:0)

您是否在用户输入时进行验证?如果是这样,您可以在第一个选项中添加行尾($),以便仅在以下情况下返回true:

  • 5是到目前为止唯一输入的字符
  • 字符串以50-55
  • 开头
const regex = /^(5$|5[1-5])/;

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