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

前端 未结 16 1646
遇见更好的自我
遇见更好的自我 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 11:58

    I suggest using moment.js which provides an easy to use method for doing this.

    interactive demo

    function validate(date){
        var eighteenYearsAgo = moment().subtract(18, "years");
        var birthday = moment(date);
    
        if (!birthday.isValid()) {
            return "invalid date";    
        }
        else if (eighteenYearsAgo.isAfter(birthday)) {
            return "okay, you're good";    
        }
        else {
            return "sorry, no";    
        }
    }
    

    To include moment in your page, you can use CDNJS:

    
    

提交回复
热议问题