cheng
cheng

Reputation: 6696

javascript regular expression validate mm/dd

s="12/15"
r=/((0?[1-9])|(1[0-2])){1}\/((0?[1-9])|(1[0-9])|(2[0-9])|(3[0-1])){1}/g
s.match(r)

> ["12/1"]

I was trying to validate date format mm/dd but the matched string missed the last digit.

Can anyone help? Thanks, Cheng

Upvotes: 4

Views: 4906

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use this regex: ^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])$

If you want matches in string, use word boundaries, e.g.:

\b(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])\b

(?x)
^
(
    0?[1-9]   # 1-9 or 01-09
    |
    1[0-2]    # 10 11 12
)
/
(
    0?[1-9]   # 1-9 or 01-09
    |
    [12][0-9] # 10-29
    |
    3[01]     # 30 31
)
$

Large regex:

(?x)
\b(?:
(?<month>
    0?[13578]
    |
    1[02]
)
/
(?<day>
    0?[1-9]
    |
    [12][0-9]
    |
    3[01]
)
|
(?<month>
    0?[469]
    |
    11
)
/
(?<day>
    0?[1-9]
    |
    [12][0-9]
    |
    30
)
|
(?<month>
    0?2
)
/
(?<day>
    0?[1-9]
    |
    [12][0-9]
)
)
\b

Upvotes: 6

stema
stema

Reputation: 92976

At first I removed some of your brackets.

One possibility to fix your problem is to use anchors

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

This would be the solution if your string is only the date. Those anchors ^ and $ ensure that the expression is matched from the start to the end.

See it here online on Regexr

The second possibility is to change the order in your last part.

(0?[1-9]|1[0-2]){1}\/(1[0-9]|2[0-9]|3[0-1]|0?[1-9]){1}

Because the first part 0?[1-9] matched your 15 your expression succeeded and that was it. If we put this to the end then at first it tries to match the numbers consisting of two digits, then it matches the 15

Upvotes: 1

Related Questions