0

I have the following regular expression to validate the date in 'mm/dd/yyyy' format. It works for '12/11/2006'. But if I use '2/3/2011', it doesn't work. Could you please correct the following expression to accept '12/11/2006' or '2/3/2011' format? Thank you for help.

var date = /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/; 
1
  • 1
    I'd suggest a simplified expression /\d?\d[ \/.-]/\d?\d[ \/.-]\d{4}/ (or similar) - that is, any one- or two-digit number for day and month. I wouldn't bother restricting these within the regex just because you're going to have to separately test the values anyway to make sure that the date isn't too high for the given month and year combination (e.g., no Feb 30, and no Feb 29 unless a leap year).
    – nnnnnn
    Mar 5, 2012 at 20:57

1 Answer 1

2
var date = /(0?[1-9]|1[012])[- \/.](0?[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/; 

Just make the 0 optional: 0?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.