How Can I Validate That Someone Is Over 18 From Their Date Of Birth?
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 %>'); var Split = Dates.value.s
Solution 1:
I think a better alternative would be to calculate the age of the user, and use that in your if statement.
See this SO answer on how to do just that:
Solution 2:
Try this.
var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
var enteredAge = getAge(enteredValue.value);
if( enteredAge > 18 ) {
alert("DOB not valid");
enteredValue.focus();
returnfalse;
}
Using this function.
functiongetAge(DOB) {
var today = newDate();
var birthDate = newDate(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/
Solution 3:
<script>functiondobValidate(birth) {
var today = newDate();
var nowyear = today.getFullYear();
var nowmonth = today.getMonth();
var nowday = today.getDate();
var b = document.getElementById('<%=TextBox2.ClientID%>').value;
var birth = newDate(b);
var birthyear = birth.getFullYear();
var birthmonth = birth.getMonth();
var birthday = birth.getDate();
var age = nowyear - birthyear;
var age_month = nowmonth - birthmonth;
var age_day = nowday - birthday;
if (age > 100) {
alert("Age cannot be more than 100 Years.Please enter correct age")
returnfalse;
}
if (age_month < 0 || (age_month == 0 && age_day < 0)) {
age = parseInt(age) - 1;
}
if ((age == 18 && age_month <= 0 && age_day <= 0) || age < 18) {
alert("Age should be more than 18 years.Please enter a valid Date of Birth");
returnfalse;
}
}
</script>
Solution 4:
After looking at various methods of doing this, I decided the simplest way was to encode the dates as 8-digit integers. You can then subtract today's code from the DOB code and check if it's greater than or equal to 180000.
functionisOverEighteen(year, month, day) {
var now = parseInt(newDate().toISOString().slice(0, 10).replace(/-/g, ''));
var dob = year * 10000 + month * 100 + day * 1; // Coerces strings to integersreturn now - dob > 180000;
}
Solution 5:
letTODAY = newDate(Date.now());
letEIGHTEEN_YEARS_BACK = newDate(newDate(TODAY).getDate() + "/" + newDate(TODAY).getMonth() + "/" + (newDate(TODAY).getFullYear() - 18));
letUSER_INPUT = newDate("2003/12/13");
// Validate Nowlet result = EIGHTEEN_YEARS_BACK > USER_INPUT// true if over 18, false if less than 18
I think this is the closest possible way to check.
Post a Comment for "How Can I Validate That Someone Is Over 18 From Their Date Of Birth?"