【问题标题】:What is the format for the card? Regex [closed]卡的格式是什么?正则表达式 [关闭]
【发布时间】:2023-03-19 18:02:01
【问题描述】:

我想验证您插入卡号的输入

我尝试了这种格式,但该字段经过验证,如果少于 16 个数字。

如何更改我的常数,以免接受少于 16 位的数字,但不能超过

const card=  /^[0-9]*$/

提前致谢!

【问题讨论】:

  • 使用 /^[0-9]{16}$/ 精确到 16 位,小于使用 {0,16}
  • “不接受少于 16 位但不超过”是否意味着“正好 16 位”?

标签: javascript regex validation


【解决方案1】:

/^[0-9]{16}$/ --> 正好是 16 位

/^[0-9]{16,20}$/ --> 16 到 20 位数字

/^[0-9]{16,}$/ --> 最少16位,无上限

/^[0-9]{0,16}$/ --> 最多 16 位

【讨论】:

    【解决方案2】:

    正好可以使用 16 位数字:

    const card = /^\d{16}$/;
    

    const card = /^[0-9]{16}$/;
    

    您可以使用少于 16 位或 16 位:

    const card = /^\d{0,16}$/;
    

    const card = /^[0-9]{0,16}$/;
    

    【讨论】:

      【解决方案3】:

      您可以使用花括号来定义有效出现的次数。使用 \d 表示数字 - 它是 [0-9] 的同义词:

      window.alert('123456789012345'.match(/^\d{0,15}$/)); // is OK
      window.alert('1234567890123456'.match(/^\d{0,15}$/)); // is not OK

      试试看:http://www.regextester.com/?fam=93816

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2015-06-09
        相关资源
        最近更新 更多