KennC.
KennC.

Reputation: 3445

Regular expression for date

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.

Upvotes: 1

Views: 517

Answers (4)

t0rx
t0rx

Reputation: 363

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");
}

Upvotes: 0

darioo
darioo

Reputation: 47213

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.

Upvotes: 2

XViD
XViD

Reputation: 306

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

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

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

Upvotes: 6

Related Questions