0

I am trying to learn how to use regular expressions. Currently, I am creating my own regular expression using JavaScript to test for a date in the format of MM-DD-YYYY.

Here is my code:

// regex for testing valid date
var regex = new RegExp("[0-9]{2}\-[0-9]{2}\-[0-9]{4}");  
regex.test("113-12-1995");

Unfortunately, this is outputing to true and I cannot figure out why. I am under the impression that {2} means it must be two digits and no more or less. It seems like it is behaving as if I had put a {2,} which would correlate to at least two digits, but that isn't what I want.

Additionally, how would I test to see if the value of the first two digits are greater than 12?

Samuel Cole
  • 521
  • 6
  • 24
  • 2
    You need to anchor it: `"^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$"` otherwise the match occurs after the first `1` - Also just to be pedantic an RE is a poor choice to validate dates, '99-99-0000' is not a date for example. – Alex K. Feb 28 '18 at 18:10
  • 2
    You can anchor your pattern `^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$`. Just to add to what @AlexK. mentioned, see [my answer here](https://stackoverflow.com/a/46414732/3600709) on matching dates including leap years, etc. Not easy and not the best way to go about dates. – ctwheels Feb 28 '18 at 18:11
  • 1
    It is matching "13-12-1995". – 001 Feb 28 '18 at 18:11

0 Answers0