正则表达式 - 信用卡验证



我正在寻找一种方法来验证信用卡模式的开始。例如,让我们以万事达卡为例。

它说(参考: 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 :(

您是否在用户键入时进行验证?如果是这样,您可以在第一个选项中添加行尾 ($(,以便它仅在以下情况下返回 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

它应该是:

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

您的正则表达式匹配以 5 开头的字符串或在其中任何位置51 55的字符串,因为^仅在|的左侧。

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

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

有关与最常用卡匹配的正则表达式,请参阅使用正则表达式验证信用卡格式?

最新更新