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
}
match(/(\d{5})/g);
Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
need to specify start and end of string
/^\d{4}$/
try this ^\d{1,2}\/\d{1,2}\/\d{4}$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With