Regular Expression for MM/DD/YYYY in Javascript

Viewed 38253

I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:

function isGoodDate(dt){
    var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
    return reGoodDate.test(dt);
}

and this is how I call it in my form validation

if(!isGoodDate(userInput[1].value)){
           alert("date not in correct format of MM/dd/YYYY");
           return false;  
        }

now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?

8 Answers

Validate (DD-MM-YYYY) format :)

function isGoodDate(dt) {
    var reGoodDate = /^(?:(0[1-9]|[12][0-9]|3[01])[\-.](0[1-9]|1[012])[\-.](19|20)[0-9]{2})$/;
    return reGoodDate.test(dt);
}

Try the below code which accepts following date formats:

MM-DD-YYYY, MM-DD-YY, DD-MM-YYYY, DD-MM-YY, MM/DD/YYYY, MM/DD/YY, DD/MM/YYYY, DD/MM/YY, MM\DD\YYYY, MM\DD\YY, DD\MM\YYYY, DD\MM\YY

function isGoodDate(dt) {
    var reGoodDate = /(?:((0\d|[12]\d|3[01])|(0\d|1[012]))[\-|\\|\/]((0\d|1[012])|(0\d|[12]\d|3[01]))[\-|\\|\/](((19|20)\d{2})|\d\d))/;
    return reGoodDate.test(dt);
}

(/^(0[1-9]|1[012])- /.- /.\d\d$/) You can use this will work definitely and this is for MM/DD/YYYY

Related