You can use RegularExpressionAttribute
with the following regex:
^([01]?\d|2[0-3]):[0-5]\d$
Pergunta
I'm currently making an enrollment system and I want something like a [Required] (attribute?) to check if the input string is in the proper time format (18:00, 20:00, 1:00, etc.), how do I do that? Is there a function for it or will it manually have to be done? Thanks.
Solução
You can use RegularExpressionAttribute
with the following regex:
^([01]?\d|2[0-3]):[0-5]\d$
Outras dicas
You can use a RegularExpression
as validation attribute:
[RegularExpression(@"^([0-1]\d|2[0-3]):([0-5]\d)$", ErrorMessage = "invalid date format")]
The regex was found here: .NET Regular expression for time 24 hr format
I would suggest a method like this:
public bool IsValidTime(string time)
{
DateTime dummyDate;
return DateTime.TryParseExact(time, new[] { "HH:mm", "H:mm" },
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault, out dummyDate);
}
This method validates 24 hour clock formats, with 1 or 2 digit hour numbers.
It gives the following results with supplied inputs:
"00:00" => true
"20:00" => true
"26:00" => false
"1:00" => true
"10:5" => false
use TimeSpan.TryParse Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded http://msdn.microsoft.com/en-us/library/3z48198e(v=vs.110).aspx