How to validate a user’s birth date with a Regular Expression in JavaScript? Is test
a preferred method for validating user input with a Regular Expression?
function myValidator() {
result = true;
var today = new Date();
var todayYear = today.getFullYear();
var userBirthDate = new Date(document.getElementById("dob").value);
var regexVar = new RegExp("([0-9]{2})\/([0-9]{2})\/([0-9]{4})");
var regexVarTest = regexVar.test(userBirthDate);
var cutOff19 = todayYear - 19;
var cutOff95 = todayYear - 95;
if (isNaN(userBirthDate)) {
dobErrMsg.innerHTML = "date of birth must be a number";
} else if (regexVarTest == false) {
dobErrMsg.innerHTML = "enter date of birth as dd/mm/yyyy";
} else if (userBirthDate >= cutOff19) {
dobErrMsg.innerHTML = "you have to be older than 19";
} else if (userBirthDate <= cutOff95) {
dobErrMsg.innerHTML = "you have to be younger than 95";
}
return result;
}
<p>
<label for="dob">Date of Birth</label>
<input type="text" name="dob" id="dob" maxlength="10" placeholder="dd/mm/yyyy" pattern="([0-9]{2})\/([0-9]{2})\/([0-9]{4})" required="required" />
<span id="dobErrMsg"></span>
</p>
<button onclick="myValidator()">Run validation</button>
There are some issues in your code as explained in the comments for missing initialization of some variables.
However the issue with regex is, when you do
it results to
This is why your regex which should pass a value such as 07/03/2010 is not passing the change value. You need to run the regex on the direct value of
So it should be something like
I think you are looking for this. Let me know if that solve your problem.
Update: I have update date validation which was missing till now.
There are several issues:
test
method, but you should really pass the input string.result
,birthday
,todayYear
.if
conditions they are treated as dates. This cannot work. You should really subtract a number of years from the current date (resulting in a date). Just comparing calendar years is not a right method to determine someone’s age. At the time of writing, someone born in January 2000 is older than 19, while someone born in December 2000 is younger than 19.^
and$
anchorsnew Date
, it will be interpreted as mm/dd/yyyy. Better first convert it to some standard format like YYYY-MM-DD. The code below does this conversion of the dd/mm/yyyy input to the YYYY-MM-DD format, before passing it to theDate
constructor.Also, since there is nothing dynamic in your regex, you can just use a regex literal, instead of calling the
RegExp
constructor.Here is the corrected code:
As to the meaning of “older than 19”: if this means that a person should be 20 years or older (and not just 19 plus one day), than don’t subtract 19, but subtract 20.