How To Validate A User's Birth Date In JavaScript With A Regular Expression?
Solution 1:
There are several issues:
- You pass a Date to the regex
test
method, but you should really pass the input string. - Several variables are not defined, including
result
,birthday
,todayYear
. - The cutoff points seem to be defined as numbers (number of years), but in the
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. - An error message saying that the date is not a number is misleading to the user who had entered "13/13/1990". It should just say the date is invalid.
- The regex should require that the input does not contain other things than just the date -- it should use
^
and$
anchors - The dd/mm/yyyy format is ambiguous. When passed to
new 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:
function myValidator() {
var birthday = document.getElementById("dob").value; // Don't get Date yet...
var regexVar = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/; // add anchors; use literal
var regexVarTest = regexVar.test(birthday); // pass the string, not the Date
var userBirthDate = new Date(birthday.replace(regexVar, "$3-$2-$1")); // Use YYYY-MM-DD format
var todayYear = (new Date()).getFullYear(); // Always use FullYear!!
var cutOff19 = new Date(); // should be a Date
cutOff19.setFullYear(todayYear - 19); // ...
var cutOff95 = new Date();
cutOff95.setFullYear(todayYear - 95);
if (!regexVarTest) { // Test this before the other tests
dobErrMsg.innerHTML = "enter date of birth as dd/mm/yyyy";
} else if (isNaN(userBirthDate)) {
dobErrMsg.innerHTML = "date of birth is invalid";
} 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";
} else {
dobErrMsg.innerHTML = "";
}
return userBirthDate; // Return the date instead of an undefined variable
}
<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>
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.
Solution 2:
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
new Date("07/03/2010");
it results to
Sat Jul 03 2010 00:00:00 GMT+0530
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
document.getElementById("dob").value
So it should be something like
var userBirthDate = document.getElementById("dob").value;
var regexVar = new RegExp("([0-9]{2})\/([0-9]{2})\/([0-9]{4})");
var regexVarTest = regexVar.test(userBirthDate);
function myValidator() {
var userBirthDate = document.getElementById("dob").value;
var regexVar = new RegExp("([0-9]{2})\/([0-9]{2})\/([0-9]{4})");
var regexVarTest = regexVar.test(userBirthDate);
alert(regexVarTest);
}
<p>
<label for="dob">Date of Birth</label>
<input type="text" name="dob" id="dob" maxlength="10" required
placeholder="dd/mm/yyyy"
pattern="([0-9]{2})\/([0-9]{2})\/([0-9]{4})"/>
<span id="dobErrMsg"></span>
</p>
<button onclick="myValidator()">Run validation</button>
Solution 3:
function myValidator() {
var result = true;
var birthday = document.getElementById("dob").value
var regexVar = new RegExp("(([012]{1})?[0-9]{1}|[3]?[01]{1})\/(([0]{1})?[0-9]{1}|[1]{1}?[012]{1})\/([12]{1}[09]{1}[0-9]{2})");
var regexVarTest = regexVar.test(birthday);
//if format is valid
if (regexVarTest){
var date_array = birthday.split('/')
var userBirthDate = new Date(date_array[2], parseInt(date_array[1])-1, date_array[0]);
var userage = userBirthDate.getFullYear();
var todayYear = new Date().getFullYear()
var cutOff19 = todayYear - 19;
var cutOff95 = todayYear - 95;
}
dobErrMsg.innerHTML = "";
if (regexVarTest == false) {
dobErrMsg.innerHTML = "enter date of birth as dd/mm/yyyy";
result = false;
} else if (isNaN(Date.parse(date_array[2]+'-'+date_array[1]+'-'+date_array[0])) || new Date(date_array[2]+'-'+date_array[1]+'-'+date_array[0]).getDate() != parseInt(date_array[0])){
dobErrMsg.innerHTML = "enter valid date";
result = false;
} else if (userage >= cutOff19) {
dobErrMsg.innerHTML = "you have to be older than 19";
result = false;
} else if (userage <= cutOff95) {
dobErrMsg.innerHTML = "you have to be younger than 95";
result = false;
}
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>
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.
Post a Comment for "How To Validate A User's Birth Date In JavaScript With A Regular Expression?"