简体   繁体   中英

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. 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.

//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}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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