How can I validate that someone is over 18 from their date of birth?

后端 未结 6 1167
一向
一向 2020-12-31 16:47

I am doing validation for Driver\'s Date of birth, it should be minimum of 18 from the current date.

var Dates = $get(\'<%=ui_txtDOB.ClientID %>\');            


        
6条回答
  •  囚心锁ツ
    2020-12-31 17:47

    Try this.

    var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
    var enteredAge = getAge(enteredValue.value);
    if( enteredAge > 18 ) {
        alert("DOB not valid");
        enteredValue.focus();
        return false;
    }
    

    Using this function.

    function getAge(DOB) {
        var today = new Date();
        var birthDate = new Date(DOB);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }    
        return age;
    }
    

    Demo here: http://jsfiddle.net/codeandcloud/n33RJ/

提交回复
热议问题