Thursday 1 January 2015

Validating Dates in JavaScript

Here we are Validate the Date Fields which are Dependent on each other i.e., The Date selected in one filed will depend on another field

function validateSomeDateField()
{   
    var dateField = document.Form.dateField.value;
    split_dateField = dateField.split('-');
    var formatted_dateField = new Date();
    formatted_dateField.setFullYear(split_pid[2], split_pid[1]-1, split_pid[0]);
   
    var currentDate = new Date();
    if( formatted_dateField >= currentDate )
    {
        alert("Date Cannot Be Future");
        document.Form.dateField.value = '';
        document.Form.dateField.focus();
        return false;
    }
   
    var dateofbirth = document.Form.dateofbirth.value;
    split_dob = dateofbirth.split('-');
    var formatted_dob = new Date();
    formatted_dob.setFullYear(split_dob[2], split_dob[1]-1, split_dob[0]);

    if( formatted_dateField <= formatted_dob )
    {
        alert("Date cannot be less than birth date.");
        document.Form.dateField.value = '';
        document.Form.dateField.focus();
        return false;
    }
    if(formatted_dob >=  formatted_dateField )
    {
        alert("Date cannot be less than birth date.");
        document.Form.dateField.value = '';
        document.Form.dateField.focus();
        return false;
    }
    return true;
}

No comments:

Post a Comment