Javascript Date Validation

I needed to validate a date in javascript. I am using moment in my current project. But for 2017-05-154 it failed and returned true for IsValid(). I created the following to handle validating dates.

function dateValid(dateText) {
    var valid = true;
    var year = 0;
    var month = 0;
    var day = 0;
    if (dateText) {
        var parts = dateText.split('/');
        if (parts.length == 1) {
            parts = dateText.split('-');
        }
        if (parts.length == 3) {
            if (parts[0].length == 4) {
                month = parseInt(parts[1]);
                day = parseInt(parts[2]);
                year = parseInt(parts[0]);
            }
            else if (parts[2].length == 4) {
                month = parseInt(parts[0]);
                day = parseInt(parts[1]);
                year = parseInt(parts[2]);
            }
            else {
                valid = false;
            }
            var date = new Date(year, month - 1, day);
            var dateMonth = date.getMonth() + 1;
            var dateDay = date.getDate();
            var dateYear = date.getFullYear();
            if (dateMonth != month || dateDay != day || dateYear != year) {
                valid = false;
            }
        }
        else {
            valid = false;
        }
    }
    else {
        valid = false;
    }
    return valid;
}

Comments are closed.