13 Jan 2015

Date Validation in JavaScript

In this tutorial we are showing a javascript function that performs date validation.
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;
}
Following are the things that are validated by this function:
  • 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.

Try it





Popular Posts

Write to Us
Name
Email
Message