1

I have a date format like: YYYY-MM-DD, as we all know that the months only contains numbers like 01,02,03,04,05,06,07,08,09,10,11,12. How can I actually write a regular expression that allows me to only get the correct months as well as dates. I could only do something like this...

var date = /[0-9]{4}\-[0-9]{2}\-[0-9]{2}/;

    function checkDate(Date)
    {
        if (date.test(Date))
        {
        alert("Valid Date");
        }
            else
            {
                    alert("Invalid Date");
            }

    }

Thus, if the date is for example, 2008-24-43. It will still return me valid date.

Thanks.

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
KennC.
  • 3,315
  • 6
  • 20
  • 18
  • 2
    I really wouldn't use `Date` as an argument name. You'll shadow the `Date` constructor function. (In general, the JavaScript convention is to use camelCase or underscoring for argument names [e.g., "date" rather than "Date", and "niftyThing" or "nifty_thing" rather than "NiftyThing"], not initial caps. Initial caps is pretty much reserved -- again, only by convention -- for constructor functions. Unless you're Microsoft.) – T.J. Crowder Nov 21 '10 at 08:46

4 Answers4

6

Parsing dates with regular expressions could be a challenging task. I would recommend you taking a look at datejs instead.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

the following regular expression matches a date in yyyy-mm-dd format from between 1900-01-01 and 2099-12-31, with a choice of four separators: - / . and white space.

/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/

source: www.regular-expressions.info

XViD
  • 306
  • 1
  • 5
2

I'd suggest not going that path using regular expressions. You'll run into more problems than needed. Rather, read for example this post to see what people have tried before.

You should use new Date() to check if inputted date is really valid. Don't reinvent the wheel.

For your example, you can use this:

var strDate = "2008-07-23";
var dateParts = strDate.split("-");

var date = new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);

Disclaimer: idea taken from linked page.

If a date is not valid, you can use strategies from this post.

Community
  • 1
  • 1
darioo
  • 46,442
  • 10
  • 75
  • 103
0

This will give you basic checking:

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$

but it will still allow things like 2001-02-29. You may be best doing a two-stage process - first do the regex for speed, then use DateTime.Parse:

try
{
    DateTime.Parse(Date);
    alert("Valid Date");
}
catch (FormatException)
{
    alert("Invalid Date");
}
t0rx
  • 363
  • 2
  • 8