3

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Kendra
  • 769
  • 1
  • 20
  • 34
  • 1
    `if (test == regEx) {` will always fail, as those two things can not be equal. See Table 4.2 here for methods that use regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – Jason P Jul 22 '13 at 15:13
  • Does this answer your question? [Check whether a string matches a regex in JS](https://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex-in-js) – Karl Knechtel Jul 09 '22 at 23:10

2 Answers2

4

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

Spokey
  • 10,974
  • 2
  • 28
  • 44
  • That worked perfectly. Like I said, I'm still learning how to use regex, so I didn't know that one. Thank you so much! – Kendra Jul 22 '13 at 15:15
0

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

alecellis1985
  • 131
  • 2
  • 15