Search code examples
c#asp.net-mvcdata-annotations

Range and DisplayFormat Attributes on TimeSpan


I am building a Scheduling Screen and need to display a Time field for users to enter the time of day for the schedule.

I'm not sure if this is the best option, but I am using a TimeSpan for the field. To validate the input, I want to use the Range attribute and the DisplayFormat attribute.

When I debug and enter a seeming valid value, the Range attribute indicates an out of range error. Can anyone see what I am doing wrong? Is TimeSpan the proper type for this usage? Any help is greatly appreciated.

Model Class:

public class Schedule
{
    public Schedule()
    {
        this.ScheduleTime = new TimeSpan(0, 0, 0);
    }

    /// <summary>
    /// The time of day for the schedule to run
    /// </summary>
    [Required, DataType(System.ComponentModel.DataAnnotations.DataType.Time),
    Display(Name = "Schedule Time", Description = "Number of Hours and Minutes after Midnight Central Timezone"),
    DisplayFormat(DataFormatString = @"{0:hh\:mm\:ss}", ApplyFormatInEditMode = true),
    Range(typeof(TimeSpan), "00:00", "23:59")]
    public TimeSpan ScheduleTime { get; set; }
}

Error Message:

Error Message


Solution

  • You know those times where you ask a question and shortly after the answer just appears right before you? This is one of those for me.

    I found this SO post: why does ASP.Net MVC Range Attribute take a Type?

    Which describes the issue as jQuery being unable to handle the Range expression so the Client Side Validation won't work, but the Server Side Validation will.

    So I removed the client validation for this field with javascript:

    <script>
        $(document).ready(function () {
            $("#ScheduleTime").rules('remove', 'range');
        });
    </script>
    

    And now the validation works properly when checking the ModelState.IsValid in the controller.