Javascript Date Validation ( DD/MM/YYYY) & Age Checking
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.
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/
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}$/;
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:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>