Javascript Date Validation ( Dd/Mm/Yyyy) & Age Checking

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

http://jsfiddle.net/P9TER/

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

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

validate date to mm/dd/yyyy format in javascript

Here's the snippet you need. All you need to pass date to below function which returns true/false if the given date is valid/invalid

function validateDate(dateValue)
{
var selectedDate = dateValue;
if(selectedDate == '')
return false;

var regExp = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dateArray = selectedDate.match(regExp); // is format OK?

if (dateArray == null){
return false;
}

month = dateArray[1];
day= dateArray[3];
year = dateArray[5];

if (month < 1 || month > 12){
return false;
}else if (day < 1 || day> 31){
return false;
}else if ((month==4 || month==6 || month==9 || month==11) && day ==31){
return false;
}else if (month == 2){
var isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day> 29 || (day ==29 && !isLeapYear)){
return false
}
}
return true;
}

The above function will:

  • Checks for proper date format as MM/DD/YYYY.
  • Checks whether the given date is valid or not. Ex: April month is having only 30 days. If we specify day as 31 for the month of April then this function will validate it as invalid date.
  • Checks for 29th day of February. It will validate as a valid date only if the specified year is a leap year.

For more info please go through the link: http://www.j2eekart.com/2015/01/date-validation-in-javascript.html

Change your code as:

<script type="text/javascript">
$(document).ready(function(){
$('.datepicker').datepicker();

$(".datepicker").on("blur", function (e){
var isValidDate = validateDate(e.target.value);
if(!isValidDate){
alert("Please enter a valid date in MM/DD/YYYY format");
}
});
});

function validateDate(dateValue)
{
var selectedDate = dateValue;
if(selectedDate == '')
return false;

var regExp = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dateArray = selectedDate.match(regExp); // is format OK?

if (dateArray == null){
return false;
}

month = dateArray[1];
day= dateArray[3];
year = dateArray[5];

if (month < 1 || month > 12){
return false;
}else if (day < 1 || day> 31){
return false;
}else if ((month==4 || month==6 || month==9 || month==11) && day ==31){
return false;
}else if (month == 2){
var isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day> 29 || (day ==29 && !isLeapYear)){
return false
}
}
return true;
}
</script>

validate dob with age verification

Since you know the date will be separated by '/' just do it the old fashion way of splitting the string into 3 and creating a date object.

var dob = document.getElementById("dob").value.split("/");

var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);

Then you can do your processing such as checking day, month, year to verify if they are between 15 and 80.

If you are not taking months and days into considerations then this simple if statement will fulfill the purpose.

var today = new Date();
var age = today.getFullYear() - date.getFullYear();

if(age >= 15 && age <= 80){
// Between age ranges.
}


Related Topics



Leave a reply



Submit