Zet
Zet

Reputation: 571

simply regex date validation

I'm trying to create simply regex validation for my mvc application. I tried:

[Required]
[RegularExpression("(\\d\\d\\/\\d\\d\\/\\d\\d\\d\\d)")]

and it is not working. I want to force customer to enter date in format 01/01/2015

Upvotes: 2

Views: 3026

Answers (2)

teo van kot
teo van kot

Reputation: 12491

Why you need regex for this case? Use DisplayFormat and DataType:

[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

I mean it just wrong to validate a date with regex. There is no easy way to validate dates like 31/02/2015 or 31/04/2015 which is not a valid date.

Upvotes: 5

rbonestell
rbonestell

Reputation: 439

It might be due to the confusion caused by escaping so many characters.

Here I have escaped the whole string by prepending @ and condensed the regex by using quantifiers to specify how many characters of each digit class to capture:

[RegularExpression(@"(\d{2}/\d{2}/\d{4})")]

However, since you're using this to validate date entries you might want to consider using a DateTime validator as teo van kot has mentioned because this regex doesn't enforce valid date values.

Upvotes: 2

Related Questions