0

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?

hata
  • 11,633
  • 6
  • 46
  • 69
qqla333
  • 47
  • 1
  • 6
  • 1
    Is there really no chance to map that attribute to some bit of code that uses `DateTime.TryParseExact`? Xcheck [this post](http://stackoverflow.com/questions/27182606/asp-mvc-5-client-validation-for-range-of-datetimes). – Wiktor Stribiżew Sep 14 '15 at 15:41

2 Answers2

2

You can use a regex like this:

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

Working demo

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
0

Try using this custom validation:

[ValidateDate]
public string Time { get; set; }
       ^^^^^^

Here is the implementation of the ValidateDate attribute:

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.");
    }
}

Note that if you plan to also accept 2:00-like values, you need to use new[] {"HH:mm", "H:mm"} instead of "HH:mm".

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I get exception in the condition: "An exception of type 'System.InvalidCastException' occurred in RadioSite.dll but was not handled in user code Additional information: Unable to cast object of type 'System.DateTime' to type 'System.String'." – qqla333 Sep 15 '15 at 08:03
  • I think you can fix it by adding `DateTime dt_value = (DateTime)value;` and replacing `(string)value` with `string.Format("{0}:{1}", dt_value.Hour, dt_value.Minute)`. – Wiktor Stribiżew Sep 15 '15 at 08:32
  • This work probably ok. Thank you!. But i I have one more question: when I enter example: 21:22:22 (with seconds) this validation is success. How do that time with seconds will be incorrect? – qqla333 Sep 15 '15 at 15:59
  • Then you need to change the property type to string, otherwise it looks meaningless. I updated the answer. I even think you can use acregex now, but I still believe that date and time validation should be done without regex. It is easier to maintain and scale with appropriate methods and classes. – Wiktor Stribiżew Sep 16 '15 at 06:08