I am trying to validate a date of birth entered into a HTML form in the format dd/mm/yyyy with a JavaScript file, for an assignment. I am only allowed to use a separate, linked JavaScript file (no embedded JavaScript in the HTML file). Also, I am not allowed to use alerts - the user must see the error message on the page itself.

I have created a JavaScript variable that stores a regex test of another variable that stores the user text input of their birth date.

The test returns that a valid date entered (e.g. 01/10/1992 or 30/06/2007) is not valid (false), and thus displays an error message.

I have tested out the regex on the RegExr website (https://regexr.com) with various date values, and it matches correctly.

I have also tested that the regex validates in HTML, and it matches the user input correctly.

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>

I am expecting the test to accept the user input date in the format dd/mm/yyyy (e.g. 07/03/2010), instead it returns the error message, "enter date of birth as dd/mm/yyyy". Why? The console shows no errors. Where is the problem?

Edit #1: regexVar.test(birthday) to regexVar.test(userBirthDate)

Edit #2: else if (regularExpressionTest == false) to else if (regexVarTest == false)

Edit #3: At the top of the post I have clarified that it is for an assignment, and I am not allowed to use embedded JavaScript (all of the JavaScript has to be in a separate, linked JavaScript file). Also, I cannot use alerts, instead the error messages must appear on the page for the user to see.

Edit #4: Added the variables:

result = true;

var today = new Date();

var todayYear = today.getFullYear();

3 Answers

0
trincot On Best Solutions

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 the Date 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";
  }
  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.

0
Deep On

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" 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>

-1
Mithun Mandal On

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.