Maciej Miśkiewicz
Maciej Miśkiewicz

Reputation: 412

MVC 4 Regular Expression in View Model - date

I am creating MVC application and in my ViewModel I am trying to validate if input is of form DD/MM/YYYY and I do this like this:

[RegularExpression(@"^[0-9]+(/)+[0-9]+(/)+[1-9]$", ErrorMessage = "Input date has to be of form DD/MM/YYYY")]

How do I do it right?

Upvotes: 0

Views: 1977

Answers (2)

Justin Marshall
Justin Marshall

Reputation: 1

If you want to keep your date as a string in the model then use the following

[RegularExpression(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$"]

Upvotes: 0

Shukizu
Shukizu

Reputation: 56

I don't think using regular expressions is the best way to do this, you can use DataType for validate and DisplayFormat for get your date formated.

your code be like something like that:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime dateValidation {get; set;}

Upvotes: 2

Related Questions