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
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.
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})$/;
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
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}$/;
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));