JavaScript Birthday Validation: Regex Format

Viewed 43

Trying to test out some JS form validation. Not sending this information to any database or anything; just trying to hammer down the format for now. All my regex checks are working fine except for birth

It seems as though there is something wrong in the regex check because when I put another check in there with a different format, it works fine. I want them to enter the birthday in mm/dd/yyyy fashion and display the proper error if not. Any help is appreciated!

    if(birth == "") {
        printError("birthErr", "Please enter your birthday");
    } else {
        var regex = '/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/';                 
        if(regex.test(birth) === false) {
            printError("birthErr", "Please enter a valid birthday");
        } else {
            printError("birthErr", "");
            birthErr = false;
        }
    }
    
1 Answers

Your does not validate leap years correctly, you can try to use the regex below, it can use to take dd/mm/yyyy, dd-mm-yyyy or dd.mm.yyyy.

^(?:(?:31(/|-|.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(/|-|.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(/|-|.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(/|-|.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

You can try this regex here

Related