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:
functionmyValidator() {
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 literalvar regexVarTest = regexVar.test(birthday); // pass the string, not the Datevar userBirthDate = newDate(birthday.replace(regexVar, "$3-$2-$1")); // Use YYYY-MM-DD formatvar todayYear = (newDate()).getFullYear(); // Always use FullYear!!var cutOff19 = newDate(); // should be a Date
cutOff19.setFullYear(todayYear - 19); // ...var cutOff95 = newDate();
cutOff95.setFullYear(todayYear - 95);
if (!regexVarTest) { // Test this before the other tests
dobErrMsg.innerHTML = "enter date of birth as dd/mm/yyyy";
} elseif (isNaN(userBirthDate)) {
dobErrMsg.innerHTML = "date of birth is invalid";
} elseif (userBirthDate > cutOff19) {
dobErrMsg.innerHTML = "you have to be older than 19";
} elseif (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><labelfor="dob">Date of Birth</label><inputtype="text"name="dob"id="dob"maxlength="10"placeholder="dd/mm/yyyy"pattern="([0-9]{2})\/([0-9]{2})\/([0-9]{4})"required="required" /><spanid="dobErrMsg"></span></p><buttononclick="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
newDate("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 = newRegExp("([0-9]{2})\/([0-9]{2})\/([0-9]{4})");
var regexVarTest = regexVar.test(userBirthDate);
functionmyValidator() {
var userBirthDate = document.getElementById("dob").value;
var regexVar = newRegExp("([0-9]{2})\/([0-9]{2})\/([0-9]{4})");
var regexVarTest = regexVar.test(userBirthDate);
alert(regexVarTest);
}
<p><labelfor="dob">Date of Birth</label><inputtype="text"name="dob"id="dob"maxlength="10"requiredplaceholder="dd/mm/yyyy"pattern="([0-9]{2})\/([0-9]{2})\/([0-9]{4})"/><spanid="dobErrMsg"></span></p><buttononclick="myValidator()">Run validation</button>
Solution 3:
functionmyValidator() {
var result = true;
var birthday = document.getElementById("dob").valuevar regexVar = newRegExp("(([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 validif (regexVarTest){
var date_array = birthday.split('/')
var userBirthDate = newDate(date_array[2], parseInt(date_array[1])-1, date_array[0]);
var userage = userBirthDate.getFullYear();
var todayYear = newDate().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;
} elseif (isNaN(Date.parse(date_array[2]+'-'+date_array[1]+'-'+date_array[0])) || newDate(date_array[2]+'-'+date_array[1]+'-'+date_array[0]).getDate() != parseInt(date_array[0])){
dobErrMsg.innerHTML = "enter valid date";
result = false;
} elseif (userage >= cutOff19) {
dobErrMsg.innerHTML = "you have to be older than 19";
result = false;
} elseif (userage <= cutOff95) {
dobErrMsg.innerHTML = "you have to be younger than 95";
result = false;
}
return result;
}
<p><labelfor="dob">Date of Birth</label><inputtype="text"name="dob"id="dob"maxlength="10"placeholder="dd/mm/yyyy"pattern="([0-9]{2})\/([0-9]{2})\/([0-9]{4})"required="required" /><spanid="dobErrMsg"></span></p><buttononclick="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?"