简体   繁体   English

JavaScript正则表达式仅匹配X位数

[英]JavaScript regular expression to match X digits only

Can someone help my pea brain figure out why my simple regular expression is not working as I am expecting/wanting it to. 有人可以帮助我的豌豆大脑弄清楚为什么我的简单正则表达式不起作用,因为我期待/想要它。

I want to match a date format of MM/DD/YYYY with exactly 2 and 4 digits, so something like 01/16/1955. 我想将MM / DD / YYYY的日期格式与2位和4位完全匹配,所以类似于01/16/1955。 My code below does that, but it also matches 2+ and 4+ digits, so something like 011/16/1955 or 01/16/19555 (1 extra digit) pass my validation as well. 我的代码如下,但它也匹配2+4+数字,所以像011/16/1955或01/16/19555(1个额外数字)的东西也通过我的验证。

//validate date of birth
var dob_label    = $date_of_birth.find('label').text().slice(0, -1),
dob_mm           = $dob_mm.val(),
dob_dd           = $dob_dd.val(),
dob_yyyy         = $dob_yyyy.val(),     
regex_two_digit  = /^\d{2}$/,
regex_four_digit = /^\d{4}$/;

if ( (regex_two_digit.test(dob_mm)) && (regex_two_digit.test(dob_dd)) && (regex_four_digit.test(dob_yyyy)) ) {
    //a button is enabled here
} else {
    //a validation error is thrown here and the button is disabled
}

需要指定字符串的开头和结尾

/^\d{4}$/

试试这个^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$

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

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