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 is below
<form name="ProcessInfo" action="#" method="POST" enctype="multipart/form-data" target="_self" onsubmit="return checkForm();">
.
.
.
.
<br>
<label for="txtDOB">Date of Birth:* </label>
<input id="txtDOB" type="text" name="txtDOB" size="12">
format: ##/##/####
<br>
.
.
.
</form>
.
.
and I did the following in my .js file
var errMessage = "";
function checkForm() {
validateName();
validateSurname();
carSelect();
validateDOB();
if (errMessage == "") {
} else {
alert(errMessage);
}
}
...
function validateDOB()
{
var dob = document.forms["ProcessInfo"]["txtDOB"].value;
var pattern = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
if (dob == null || dob == "" || !pattern.test(dob)) {
errMessage += "Invalid date of birth\n";
return false;
}
else {
return true
}
}
I tried to check if its valid with regular expression but I always get an alert even if I type the date correctly. And how can I seperate the DD / MM / YYYY to calculate the age?
Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.
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/
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With