19

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
}
magenta placenta
  • 275
  • 1
  • 4
  • 10
  • Why not have a single input and use date.js to parse and format it to your preferred format... combined with a placeholder works very well... – Tracker1 Jan 30 '11 at 10:04

2 Answers2

38

need to specify start and end of string

/^\d{4}$/
Crayon Violent
  • 31,449
  • 5
  • 53
  • 77
  • anyways, why not use dropdowns instead? – Crayon Violent Jan 30 '11 at 01:17
  • 1
    I did try that and it doesn't work for me. No dropdowns because users are keyboard enterers. The revised code still allows more than 2 or 4 digits. It does validate digits (I can't do 'aa'), but it still allows too many digits which I can't figure out...*Edit* wait, it seems to be working but I'm telling you, I tried the beginning/end characters multiple times, wtf??? – magenta placenta Jan 30 '11 at 01:23
  • lol /shrug...maybe you had some kind of refresh/cache thing going on and the code didn't actually update – Crayon Violent Jan 30 '11 at 01:46
1

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

sjngm
  • 11,933
  • 13
  • 78
  • 107
  • 6
    When you provide an answer like this, you should also explain why what you're suggesting will work correctly where the code in the question won't. – Jonathan Leffler Nov 24 '12 at 20:40