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

前端 未结 16 1528
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2020-12-01 12:04

    You have used regular expression for this format : DD - MM- YYYY

    If you need this format DD/MM/YYYY use

    var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    
    0 讨论(0)
  • 2020-12-01 12:06

    You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you

    0 讨论(0)
  • 2020-12-01 12:08

    If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

    var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    

    http://jsfiddle.net/P9TER/

    0 讨论(0)
  • 2020-12-01 12:10

    If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

       
    var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;

    0 讨论(0)
  • 2020-12-01 12:10

    Using pattern and check validate:

    var input = '33/15/2000';
    
    var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;
    
    alert(pattern.test(input));
    
    0 讨论(0)
提交回复
热议问题