Regular expression validation time

时间:2015-09-14 15:24:56

标签: regex validation time asp.net-mvc-5

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?

2 个答案:

答案 0 :(得分:1)

你可以使用这样的正则表达式:

^([01][0-9]|2[0-3]):[0-5][0-9]$

<强> Working demo

答案 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"