0

I have this regex

^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$

and it validates this time format: hh:mm AM|am|PM|pm, for example 04:25 pm, 11:20 am

How do I make 4:25 pm (no 0 before 4) be also valid? in other word make h:mm be valid time format in addition of hh:mm Please explain so I can understand what you do. Thanks!

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110
  • `DateTime.TryParseExact` with `"h:mm tt"`. Implement your own validator. Do it [as it should be done](http://stackoverflow.com/questions/32624800/swedish-ssn-regular-expression-reject-users-under-a-specific-age/32625321#32625321). Regex is not your friend with datetime validation. – Wiktor Stribiżew Sep 17 '15 at 23:03
  • Are you interested in a proper (non-regex) approach? If yes, post the relevant code. – Wiktor Stribiżew Sep 17 '15 at 23:13

2 Answers2

1

Try this:

^([1-9]|1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1

Here is a non-regex way to write a DateTime validation in MVC app:

[Required(ErrorMessage = "This value is required!")]
[MyValidateTime]
public string TimeValue { get; set; }

And here is the MyValidateTime code:

public class MyValidateTime: ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {                 
        DateTime dt;
        if (DateTime.TryParseExact((string)value, new[] { "hh:mm tt", "h:mm tt" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            return ValidationResult.Success;
        else
            return new ValidationResult("Correct time formats: 01:00 AM or 1:00 AM");
    }
}

Here, the allowed time formats are:

  • hh:mm tt (01:00 AM)
  • h:mm tt (1:00 AM)

See more DateTime formats at Custom Date and Time Format Strings MSDN page

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563