本文介绍了JavaScript正则表达式仅匹配X位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我的豌豆大脑弄清楚为什么我的简单正则表达式不起作用,因为我期待/想要它。
Can someone help my pea brain figure out why my simple regular expression is not working as I am expecting/wanting it to.
我想匹配日期格式MM / DD / YYYY,完全 2和4位数,所以类似于01/16/1955。我的下面的代码就是这样,但它也匹配 2 + 和 4 + 数字,所以像011/16/1955或01/16/19555(1个额外数字)也通过我的验证。
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
}
推荐答案
需要指定字符串的开头和结尾
need to specify start and end of string
/^\d{4}$/
这篇关于JavaScript正则表达式仅匹配X位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!