How to validate a user's birth date in JavaScript with a Regular Expression?

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>

64 thoughts on “How to validate a user's birth date in JavaScript with a Regular Expression?”

  1. hello there and thank you for your info – I have definitely picked up anything new from right here.
    I did however expertise several technical points using this site, since I experienced to reload the site lots of times
    previous to I could get it to load correctly.
    I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will often affect your
    placement in google and can damage your quality score if ads and
    marketing with Adwords. Anyway I am adding this RSS to my email and could look out for a lot more
    of your respective intriguing content. Make sure
    you update this again very soon. http://www.deinformedvoters.org/vidalista-online

    Reply

Leave a Comment