Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 590
magenta placenta Avatar asked Jan 30 '11 01:01

magenta placenta


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

How does regex match 4 digits?

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.

Which regex matches one or more digits?

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.

How do you find digits in regex?

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


2 Answers

need to specify start and end of string

/^\d{4}$/
like image 167
Crayon Violent Avatar answered Oct 12 '22 02:10

Crayon Violent


try this ^\d{1,2}\/\d{1,2}\/\d{4}$

like image 37
Darrell Robert Parker Avatar answered Oct 12 '22 02:10

Darrell Robert Parker