Date Validation

Validate a date

HTML

<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
Month
<input id="month" value="1" type="text" maxlength="2" />

Day
<input id="day" value="1" type="text" maxlength="2" />

Year
<input id="year" value="2001" type="text" maxlength="4" />

<br />

<button id="btValidate">Validate</button>

<br />

<div id="alert" style="width=200px" > </div> <!-- end #alert div -->

CSS

input
{
    width: 35px;
    text-align: center;
}

p
{
    color: #FFF;
    padding: 3px;
}

#alert
{
    height: 25px;
    width: 10px;
    margin-top: 5px;
}

JavaScript

var compareDate, checkDates = false;
var validateObject = {
    init: function(year, month, day) {
        return this.compareDate.init(year, month, day);
    },
    compareDate: {
        init: function(year, month, day) {
            var isValid = false;
            // Compensate for zero based index, if month was not
            // subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
            month -= 1;

            // Create a new date object with the selected
            // year, month, and day values and retrieve the
            // milliseconds from it.
            var mSeconds = (new Date(year, month, day)).getTime();
            var objDate = new Date();

            // Set the time of the object to the milliseconds 
            // retrieved from the original date. This will
            // convert it to a valid date.
            objDate.setTime(mSeconds);

            // Compare if the date has changed, if it has then
            // the date is not valid 
            if (objDate.getFullYear() === year&&
                objDate.getMonth() === month &&
                objDate.getDate() === day) 
            {                
                if(objDate <= new Date())
                {
                    isValid = true;
                }                   
            }
            return isValid;
        }
    }
};

$(function() {
    var validateButton = $('#btValidate');

    validateButton.click(function(e) {
        var month = parseInt(document.getElementById('month').value, 0),
            day = parseInt(document.getElementById('day').value, 0),
            year = parseInt(document.getElementById('year').value, 0),
            alertBox = $('#alert'),
            isValid = false;
        
        isValid = validateObject.init(year, month, day);
        var color, message;
        
        if (isValid === true) 
        {
            color = "#008000";
            message = "Your date is valid!";
        } 
        else if (isValid === false)
       ...