Date does not match RegExp, although formatted correctly

I am currently working on a program. I was instructed to work with entering formatting dates using regex and jquery. Having problems, I decided to run 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'm still pretty new to javascript, jquery and regex, so I don't understand why the test date does not match the first regex.

Any ideas would be greatly appreciated! I have code for formatting, but I have to check if the dates after formatting match where this code is.

+4
source share
1 answer

You cannot directly compare string with regex, 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

+4
source

Source: https://habr.com/ru/post/1492733/


All Articles