0

I have regex which validates date (MM/dd/yyyy) format.

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

Valid format example: 03/04/1991

If i write 3/04/1991 or 03/4/1991 instead of 03 or 04 it doesn't work.

How to validate date format with/without zeros?

2 Answers2

1

You could make the 0 optional, add 2 digits \d\d after matching 19 or 20 and use word boundaries \b.

If you don't need the capturing groups, you can use non capturing (?: groups`

\b(?:0?[1-9]|1[012])[- /.](?:0?[1-9]|[12][0-9]|3[01])[- /.](?:19|20)\d\d\b

Regex demo

If you want to have consistent delimiters, you could make use of a capturing group and a backreference \1 to what is captured in the group to not match for example 3/04-1991

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

Regex demo

The fourth bird
  • 96,715
  • 14
  • 35
  • 52
1

I see you are trying to use regular expressions to force input validation of numbers. It is doable, but usually not recommended - it is simpler and more readable to just capture digits and verify validity of the captured data later: \d{1,2}[/.-]\d{1,2}[/.-]\d{4}

Especially if you want to reach the year 2100 ;-) This will also allow you to return a more informative error message to the user: instead "error parsing input" you might be able to say things like "Invalid month 13" or some such.

That being said, if you make your regular expression complicated enough you can enforce every requirement: (0?[1-9]|[12]\d|3[0-1])

Guss
  • 24,799
  • 13
  • 87
  • 109