Paul Hashmi
Paul Hashmi

Reputation: 466

Javascript Regex for DD/MM only

I have looked all over stack overflow and tried making and changing regex's to suit my needs but do to my very limited understanding of them I am coming unstuck...

I need to make a Javascript regular expression to check DD/MM. I can get DD/MM/YYYY working but this is not what I need.

What I have is ^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$. This checks for DD/MM/YYYY but I when I try to simply truncate the end I get errors. I know limited knowledge read about regex's in javascript...Links appreciated.

Upvotes: 1

Views: 593

Answers (3)

Toto
Toto

Reputation: 91385

To avoid matching dates like 00/00, use:

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

Demo

According to comment, you said " I will be making a function to check it if it passes the regex.", So it's enough to use simpler regex:

^\d\d\/\d\d$

Upvotes: 0

Lee Developer
Lee Developer

Reputation: 98

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

Upvotes: 0

Riscie
Riscie

Reputation: 4629

Edited - simplified version as mentioned in the comments below

Based on your regex, this would be what you are looking for:

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

But as Tim has pointed out in the comments, it is not bullet proof to do it that way.

You can look at the regex here: https://regex101.com/r/oQ2k6v/1 regex101 is a very nice site for regexes. It explains every part of the regex.

Upvotes: 1

Related Questions