Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Date | Q842 [ previous next ]

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

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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.