开发者

Regular Expression date validation error

开发者 https://www.devze.com 2023-03-20 19:21 出处:网络
I\'m very new in regular expression and I\'m trying to validate date using following regular expression here:

I'm very new in regular expression and I'm trying to validate date using following regular expression here:

^[1-3开发者_开发技巧1]\.[1-12]\.[1999-2005]$

but I'm getting an output as "invalid reguar expression"

Could anyone please tell me what's wrong I'm doing in above regular expression?


Regular expressions can't match ranges of numbers, like you're doing with [1-31]. It can only match ranges of characters. You would need to match [1-31] as ([12]?[0-9]|3[01]) instead—it's not the most friendly thing in the world.


You can use:

[0-9]{2}.[0-9]{2}.[0-9]{4}

or

^(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).(19|20)[0-9]{2}$

both will match your date but wont validate it. I doubt that regular expression is a good way to validate a date due to the fact that you must check between 30 and 31 and also 28 plus leap years.

Probably there is a regular expression which handle all combination including leap years. But I recommend to use the existing function of your environment.

For example with PHP use checkdate() or the date class if you use Ruby.


try this:

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

it can match following strings~

12.12.1999
12-12-1999
12 12 1999
12/12/1999


I do that, it worked perfectly ...

for(var i=0; i<100;i++){
    if( /^([1-9]|[1-2][0-9]|[3][0-1])$/.test(i) ) {
        console.log(i);
    }
}
// display only the range of 1 to 31 and disregards the 32-100
0

精彩评论

暂无评论...
验证码 换一张
取 消