Javascript Date Validation ( DD/MM/YYYY) & Age Checking

前端 未结 16 1593
遇见更好的自我
遇见更好的自我 2020-12-01 11:09

I\'ve started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.

What my HTML code includes

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 12:04

    I'd utilize the built in Date object to do the validation for me. Even after you switch from - to / you still need to check whether the month is between 0 and 12, the date is between 0 and 31 and the year between 1900 and 2013 for example.

    function validateDOB(){
    
        var dob = document.forms["ProcessInfo"]["txtDOB"].value;
        var data = dob.split("/");
        // using ISO 8601 Date String
        if (isNaN(Date.parse(data[2] + "-" + data[1] + "-" + data[0]))) {
            return false;
        }
    
        return true;
    }
    

    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Example:_Using_parse for more information.

提交回复
热议问题