Search code examples
javascriptjqueryregexalertcontrol-flow

Jquery if Condition that will call an Alert if string not in proper format


Basically, I am trying to craft an if condition that will alert users if the do not enter their date in the proper format, i.e. the format (2011-09-20) it will alert users to this fact. Thanks in advance!


Solution

  • Just use a regular expression (and then check if it can be parsed into an actual date)

    var testValue = "2011-09-91";
    
    if(!testValue.match(/^[0-9]{4}(\-[0-9]{2}){2}$/) || isNaN(new Date(testValue)))
    {
        alert("failure");
    }