Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q842 How can I validate a date to be in the format dd/mm/yyyy?

You are here: irt.org | FAQ | JavaScript | Date | Q842 [ previous next ]

Try:

<SCRIPT LANGUAGE="JavaScript"><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }

var reason = '';

function isValidDate (myDate,sep) {
// checks if date passed is in valid dd/mm/yyyy format

    if (myDate.length == 10) {
        if (myDate.substring(2,3) == sep && myDate.substring(5,6) == sep) {
            var date  = myDate.substring(0,2);
            var month = myDate.substring(3,5);
            var year  = myDate.substring(6,10);

            var test = new Date(year,month-1,date);

            if (year == y2k(test.getYear()) && (month-1 == test.getMonth()) && (date == test.getDate())) {
                reason = '';
                return true;
            }
            else {
                reason = 'valid format but an invalid date';
                return false;
            }
        }
        else {
            reason = 'invalid spearators';
            return false;
        }
    }
    else {
        reason = 'invalid length';
        return false;
    }
}

function tellMeIfInvalid(myDate) {
    if (isValidDate(myDate,'/'))
        document.write(myDate + ' = valid date<BR>');
    else
        document.write(myDate + ' = ' + reason + '<BR>');
}

tellMeIfInvalid('21/02/1999');
tellMeIfInvalid('2190291999');
tellMeIfInvalid('2/02/1999');
tellMeIfInvalid('21/2/1999');
tellMeIfInvalid('21/02/199');
tellMeIfInvalid('32/02/1999');
tellMeIfInvalid('21/02/1999');
//--></SCRIPT>

Feedback on 'Q842 How can I validate a date to be in the format dd/mm/yyyy?'

©2018 Martin Webb