简体   繁体   中英

JavaScript regular expression to get valid date format “MM/dd/yyyy”

I am learning JavaScript Regular Expression.

I am writing a function to check valid date format, 'MM/dd/yyyy'.

function isValidDate(dateStr) {
    var result = dateStr.match(/^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/(199\d)|([2][0]\d{2})$/);
    if(result)
        return true;
    return false;
}

It works fine, but I got some issues.

01/01/2014 // return true
01/1/2014  // return true (it should return false)
1/01/2014  // return true (it should return false)

I don't want the function to return true when the month.length is 1. I want to make sure that the month.length == 2 && the date.length == 2. How can I modify my regular expression?

EDIT

01/01/20 // return true (it should return false)

How can I make sure that the year.length == 4?

In your pattern, the leading zeros are optional because of the 'zero-or-one' quantifiers ( ? ). Simply remove them to make the zeros required.

Also, you need to wrap your year portion in a single group, and [2][0] can be simplified to 20 . Try this:

/^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(199\d|20\d{2})$/

Finally, You can simply use test rather than match :

function isValidDate(dateStr) {
    return /^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(199\d|20\d{2})$/.test(dateStr);
}

This will give you the results you want:

  • isValidDate("01/01/2014")true
  • isValidDate("01/1/2014")false
  • isValidDate("1/01/2014")false

尝试这个:

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

Here's what I'd go with:

/^(0)[1-9]{1}|(1)[0-2]{1}\\/([0-2]{1}[0-9]{1}|3[0-1]{1})\\/\\d{4}$/

It depends on your application -- you said you wanted four digit years, but didn't specify recent years, so I left out the restriction on dates being > 199*

You can test it here: http://regexr.com/39ae1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM