Tuesday, 29 November 2011

How to validate Date format in Javascript?

Validate the input Date text is very common in web application. My solution is combine Regular Express and Date object. Using regular express to validate the text under the special pattern(yyyy-MM-dd etc.). Using Date object to validate the year,month, day is reasonable.

function dateValidator(text) {
    var pattern = /^([1-9]\d{3})-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$/;
    if (pattern.test($.trim(text))) {
        var datePart = text.split('-');
        var year = parseInt(datePart[0], 10);
        var month = parseInt(datePart[1], 10) - 1;
        var day = parseInt(datePart[2], 10);
        var date = new Date(year, month, day, 0, 0, 0);

        var y = date.getFullYear();
        var m = date.getMonth();
        var d = date.getDate();

        if ( year == y && month== m && day == d) {
           return true;
        }
    }
    return false;
}

No comments:

Post a Comment