I want do validation time(format HH:MM
) using regular expression. I have :
[DataType(DataType.Time)]
[RegularExpression(@"^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$", ErrorMessage = "Time format HH:MM ")]
public System.DateTime Time { get; set; }
And when I add time in textbox in form dynamic validation (side client) is ok. When i write example 43:444
it is select. When I write example 12:43
is ok (does not detect the error) but when I click submit, ErrorMessage was showed, although format is ok. How i can repair it?
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试使用此自定义验证:
[ValidateDate]
public string Time { get; set; }
^^^^^^
以下是ValidateDate
属性的实现:
public class ValidateDate: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dateValue;
if (DateTime.TryParseExact(value, "HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dateValue))
return ValidationResult.Success;
else
return new ValidationResult("Expected time format: HH:mm.");
}
}
请注意,如果您计划同时接受2:00
之类的值,则需要使用new[] {"HH:mm", "H:mm"}
代替"HH:mm"
。