Kendra
Kendra

Reputation: 769

Date not matching RegExp, though correctly formatted

I ran into a problem with formatting date inputs using regex and jquery. I managed to narrow it down to this test code:

function formatDate() {
    var regEx = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)\d\d$/;
    var test = "02/20/1901";
    var obj = $('.format');
    var febRexEx = /^(02)[\/](3[01])[\/](19|20)\d\d$/;
    if (test == regEx) {
        alert("Matches Regular Expression 1.");
        if (test == febRexEx) {
            alert("Bad date!\nMatches Regular Expression 2!");
        } else {
            alert("Not a bad date.\nDoesn't match Regular Expression 2.");
        }
    } else {
        alert("Bad date!\nDoesn't match Regular Expression 1!");
    }
}

I think the test date should match against the first regular expression, but the code tells me that it doesn't - I get the Bad date! Doesn't match Regular Expression 1! alert message. Why does this happen, and how can I fix it?

Upvotes: 3

Views: 300

Answers (2)

alecellis1985
alecellis1985

Reputation: 129

You should use moment.js https://momentjs.com/ with that lib you can validate any date and parse is as you wish

Upvotes: -1

Spokey
Spokey

Reputation: 10994

You cannot compare a string with a regular expression directly, use something like match

  function formatDate() {
      var regEx = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)\d\d$/;
      var test = "02/20/1901";
      var obj = $('.format');
      var febRexEx = /^(02)[\/](3[01])[\/](19|20)\d\d$/;
      if (test.match(regEx)) {
          alert("Matches Regular Expression 1.");
          if (test.match(febRexEx)) {
              alert("Bad date!\nMatches Regular Expression 2!");
          } else {
              alert("Not a bad date.\nDoesn't match Regular Expression 2.");
          }
      } else {
          alert("Bad date!\nDoesn't match Regular Expression 1!");
      }
  }

FIDDLE

Upvotes: 4

Related Questions