Click here to Skip to main content
11,413,676 members (77,043 online)
Click here to Skip to main content

Tagged as

JavaScript Date Validation

, 29 Nov 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
JavaScript Date Validation
For a few days now, I have been battling with the problem of JavaScript date validation. I wanted to validate text inputed by a user as they were typing to tell them if it was a valid date. After much searching on the internet, I found nothing that worked. So I wrote the following code to do the job, it is a simple but effective isDate function:
 
//Value parameter - required. All other parameters are optional.
function isDate(value, sepVal, dayIdx, monthIdx, yearIdx) {
    try {
        //Change the below values to determine which format of date you wish to check. It is set to dd/mm/yyyy by default.
        var DayIndex = dayIdx !== undefined ? dayIdx : 0; 
        var MonthIndex = monthIdx !== undefined ? monthIdx : 0;
        var YearIndex = yearIdx !== undefined ? yearIdx : 0;
 
        value = value.replace(/-/g, "/").replace(/\./g, "/"); 
        var SplitValue = value.split(sepVal || "/");
        var OK = true;
        if (!(SplitValue[DayIndex].length == 1 || SplitValue[DayIndex].length == 2)) {
            OK = false;
        }
        if (OK && !(SplitValue[MonthIndex].length == 1 || SplitValue[MonthIndex].length == 2)) {
            OK = false;
        }
        if (OK && SplitValue[YearIndex].length != 4) {
            OK = false;
        }
        if (OK) {
            var Day = parseInt(SplitValue[DayIndex], 10);
            var Month = parseInt(SplitValue[MonthIndex], 10);
            var Year = parseInt(SplitValue[YearIndex], 10);
 
            if (OK = ((Year > 1900) && (Year < new Date().getFullYear()))) {
                if (OK = (Month <= 12 && Month > 0)) {

                    var LeapYear = (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0));   
                    
                    if(OK = Day > 0)
                    {
                        if (Month == 2) {  
                            OK = LeapYear ? Day <= 29 : Day <= 28;
                        } 
                        else {
                            if ((Month == 4) || (Month == 6) || (Month == 9) || (Month == 11)) {
                                OK = Day <= 30;
                            }
                            else {
                                OK = Day <= 31;
                            }
                        }
                    }
                }
            }
        }
        return OK;
    }
    catch (e) {
        return false;
    }
} 
 
Just copy the above function and call isDate(value) where value is a string containing a valid or invalid date. The function returns a bool true if the string was a date and false if it wasn't. Hope this helps! Smile | <img src= " />
 
EDIT: Thanks to Member 2792937 for bringing a bug to my attention.
 
Both parseInt('08') and parseInt('09') return zero because the function tries to determine the correct base for the numerical system used. In JavaScript, numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.
 
To fix this, just add the second parameter for parseInt, the base to be used for the conversion. The correct calls should be parseInt('08', 10) and parseInt('09', 10).

(From http://www.ventanazul.com/webzine/articles/issues-parseint-javascript[^])
 
I have modified my code to fix this issue.

EDIT: Now includes optional parameters for specifying separator value and the indexes. To miss out a parameter simply pass in undefined. Thanks to Lester Callif for the suggestions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ed Nutting
Student
United Kingdom United Kingdom
Hi,

I am Edward Nutting, born March 1996 and I am currently an Electrical and Electronic Engineering undergraduate at the University of Bristol, UK. I've been self-teaching programming since I was eight years old and have dabbled in many different areas from web development (where I had my own advertising startup) to low level operating system stuff (my current project Fling OS).

The articles and code on this profile are some of my early work (from when I was aged about 13 to 16) but despite my young age, it has been well received by CodeProject users. My more recent work has been for companies or on projects hosted on GitHub, CodePlex or BitBucket.

I keep an eye on many things techy and am open to any and all ideas, so please feel free to contact me if you think I can help! Smile | :)

Cheers,
Ed Nutting
Follow on   Twitter   LinkedIn

Comments and Discussions

 
BugDefault day, month, year indexes will not work. Also, param sepVal is not working properly. Pin
Min Htun Zaw, 5-Oct-13 1:51
memberMin Htun Zaw5-Oct-13 1:51 
SuggestionNewer version [modified] Pin
Master DJon, 5-Dec-12 7:24
memberMaster DJon5-Dec-12 7:24 
GeneralRe: Newer version Pin
joni8a, 5-Mar-13 4:30
memberjoni8a5-Mar-13 4:30 
AnswerRe: Newer version Pin
Master DJon, 5-Mar-13 8:10
memberMaster DJon5-Mar-13 8:10 
AnswerRe: Newer version Pin
Master DJon, 5-Mar-13 9:55
memberMaster DJon5-Mar-13 9:55 
QuestionShorter code Pin
redphx, 4-Dec-12 21:13
memberredphx4-Dec-12 21:13 
QuestionAlternative to parseInt() Pin
Xunrel, 4-Dec-12 7:03
memberXunrel4-Dec-12 7:03 
QuestionImpressive, but have a couple of mods that should take care of both the date format and the separator for diff countries. Pin
Lester Callif, 27-Nov-12 16:46
memberLester Callif27-Nov-12 16:46 
AnswerRe: Impressive, but have a couple of mods that should take care of both the date format and the separator for diff countries. Pin
Ed Nutting, 29-Nov-12 11:52
memberEd Nutting29-Nov-12 11:52 
GeneralRe: Impressive, but have a couple of mods that should take care of both the date format and the separator for diff countries. Pin
Lester Callif, 29-Nov-12 13:50
memberLester Callif29-Nov-12 13:50 
AnswerRe: Impressive, but have a couple of mods that should take care of both the date format and the separator for diff countries. Pin
Ed Nutting, 30-Nov-12 10:16
memberEd Nutting30-Nov-12 10:16 
AnswerRe: Impressive, but have a couple of mods that should take care of both the date format and the separator for diff countries. Pin
Ed Nutting, 29-Nov-12 12:01
memberEd Nutting29-Nov-12 12:01 
QuestionJust one bug in February Pin
Member 3240905, 21-Nov-12 13:37
memberMember 324090521-Nov-12 13:37 
AnswerRe: Just one bug in February Pin
Ed Nutting, 25-Nov-12 12:09
memberEd Nutting25-Nov-12 12:09 
QuestionDesign flaw in your code Pin
Member 9428796, 13-Sep-12 14:38
memberMember 942879613-Sep-12 14:38 
AnswerRe: Design flaw in your code Pin
Ed Nutting, 13-Sep-12 21:26
memberEd Nutting13-Sep-12 21:26 
BugYear Validation Pin
XtremLucky, 24-Apr-12 4:05
memberXtremLucky24-Apr-12 4:05 
GeneralRe: Year Validation Pin
Ed Nutting, 24-Apr-12 7:16
memberEd Nutting24-Apr-12 7:16 
GeneralRe: Year Validation Pin
greg_ryan, 17-Jul-12 13:54
membergreg_ryan17-Jul-12 13:54 
GeneralMinor Bug Fix for the non-slash people... Pin
Ed Nutting, 13-Mar-12 13:11
memberEd Nutting13-Mar-12 13:11 
GeneralI am *very* surprised that none of our North American friend... Pin
Peter_in_2780, 26-Sep-11 17:15
memberPeter_in_278026-Sep-11 17:15 
GeneralRe: Yes I guess that is a little surprising. But then again, I w... Pin
Edward Nutting, 26-Sep-11 21:19
memberEdward Nutting26-Sep-11 21:19 
GeneralReason for my vote of 5 found to be complete, simple and ele... Pin
rquadros, 25-Jul-11 13:34
memberrquadros25-Jul-11 13:34 
QuestionBug with year validation Pin
Member 8420901, 21-Nov-11 6:59
memberMember 842090121-Nov-11 6:59 
AnswerRe: Bug with year validation Pin
Edward Nutting, 21-Nov-11 10:42
memberEdward Nutting21-Nov-11 10:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150427.2 | Last Updated 29 Nov 2012
Article Copyright 2011 by Ed Nutting
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid