Validating time-only input in asp.net MVC unobtrusive validation

后端 未结 3 1360
野性不改
野性不改 2020-12-11 01:08

I have two separate fields on the page: one for date and one for time.

This is the model:

[Required]
[DisplayFormat(ApplyFormatInEditMode = true, Dat         


        
3条回答
  •  粉色の甜心
    2020-12-11 01:39

    Honestly the easiest way to achieve this is to use a regular expression validator for it. Here is an example.

    [RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$", ErrorMessage = "Invalid Time.")]
    

    The unobtrusive validation should work just fine with this expression.

    Hope this can help you!

    EDIT

    I've fixed the regular expression which started throwing errors in the console because of some illegal characters. Also, you will need a string property wrapper for this property or else it will always look for a valid DateTime.

    Below is what you should be binding to.

    Model:

    public DateTime? StartTime { get; set; }
    
    [Required]
    [RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$", ErrorMessage = "Invalid Time.")]
    public string StartTimeValue
    {
        get
        {
            return StartTime.HasValue ? StartTime.Value.ToString("hh:mm tt") : string.Empty;
        }
    
        set
        {
            StartTime = DateTime.Parse(value);
        }
    }
    

    View:

    @Html.TextBoxFor(m => m.StartTimeValue)
    

提交回复
热议问题