Reputation: 4070
In one of my models I'm using the following property :
[Required(ErrorMessage = "Please enter the duration of the service")]
[RegularExpression(@"^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$", ErrorMessage = "Use format HH:MM only")]
public TimeSpan Duration { get; set; }
I used this regular expression to make sure that the duration`s format will be in HH:mm.
Every time that I tried to insert a value in that format I got the error message "Usage format HH:MM only". Once I removed the regular expression annotation I successfully saved an HH:MM (format string but I realized that it was saved in another format (HH:MM:SS). I tried to change the regular expression to the following annotation :
[RegularExpression(@"^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$", ErrorMessage = "Use format HH:MM:SS only")]
and now I can save duration in this format. It seems that when I try to save an HH:MM format it is automatically converted to HH:MM:SS and that's why it is failing in the annotation check.
How can I handle this issue? I don't want to enter the seconds of some flow, just the hours and the minutes.
Upvotes: 1
Views: 701
Reputation: 4070
I used the following annotation to solve the problem :
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm}")]
[RegularExpression(@"((([0-1][0-9])|(2[0-3]))(:[0-5][0-9])(:[0-5][0-9])?)", ErrorMessage = "Time must be between 00:00 to 23:59")]
Upvotes: 0
Reputation: 2104
The RegularExpressionAttribute calls the ToString() method of the TimeSpan
, which results in the format you describe (i.e. including seconds). You could just create a customized ValidationAttribute
based on the RegularExpressionAttribute
, where you include the format @"hh\:mm"
when calling ToString
on the TimeSpan
.
Upvotes: 3