I have following property in my Model Metadata class:
[Required(ErrorMessage = "Spent On is required")]
[RegularExpression(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]",
ErrorMessage = "Please enter date in mm/dd/yyyy format")]
[DataType(DataType.Date)]
[DisplayName("Spent On")]
public DateTime SpentOn { get; set; }
But whenever I call ModelState.IsValid it always returns false because regex is not validating. I have matched the entered date (08/29/2010) against new regex using same pattern and it matches perfectly.
What am I doing wrong?
That’s because regex applies to strings and not
DateTimeproperties. If the user enters an invalid string which cannot be parsed to aDateTimeinstance from the model binder it will add a generic error message before your regex pattern executes.You have a couple of possibilities: