Bagzli
Bagzli

Reputation: 6569

Regex Specific Date Format

I was wondering if somebody could point me to a regex code that validates for this: ####/##/##

Example: 1990/05/25

The second number 0 can only be 0 or 1 and the number 2 and only be 0, 1, 2, or 3. Other than that all other numbers in this set are allowed (0-9).

The code should validate that there is only 9 or 10 characters in total including the slashes.

Upvotes: 1

Views: 6911

Answers (3)

Bathsheba
Bathsheba

Reputation: 234665

Try this (edit following Jerry)

[0-2][0-9]{3,3}/[0|1][0-9]/[0-3][0-9]

Mess about with the {a,b} notation to change the length of the general digits, it means between a and b of the preceding expression inclusive. It's unclear in your question where you want the digit flexibility to be.

E.g. to emit 2013/5/29, use

 [0-2][0-9]{3,3}/[0|1]{0,1}[0-9]/[0-3][0-9]

Upvotes: 2

Jerry
Jerry

Reputation: 71538

If you only want to validate this format, you can use a regex like...

^\d{1,4}\/[01]?\d\/[0-3]\d$

I tested it a bit on some dates here.

This will match:

1990/01/01
2012/13/34
2013/1/39
9999/0/00

But reject:

23121/32/44
12/05/013
013/000/00

If you want to reject invalid dates as well such as 2013/02/29, you can check out this thread.

Upvotes: 3

Norman H
Norman H

Reputation: 2262

For all things regex I have found this website to be an invaluable resource. http://www.regular-expressions.info/reference.html

Specifically this page should get you what you need and contains a full explanation of how to go about validating date input format (not value) via Regular Expressions.

http://www.regular-expressions.info/dates.html

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

would match

yyyy-mm-dd

Upvotes: 1

Related Questions