Range and DisplayFormat Attributes on TimeSpan

老子叫甜甜 提交于 2020-01-01 06:27:08

问题


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:


回答1:


I know this is an old post, but i was able to keep the client side validation using a regular expression rather than the range validation like so:

    [Display(Name = "Schedule Time ")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm}")]
    [RegularExpression(@"((([0-1][0-9])|(2[0-3]))(:[0-5][0-9])(:[0-5][0-9])?)", ErrorMessage = "Time must be between 00:00 to 23:59")]
    public System.TimeSpan? ScheduleTime { get; set; }



回答2:


I found this question while looking for a similar problem and I want to say for the records that range validation works well in ASPNET Core 2 and JQuery v2.2.0.

[Range(typeof(TimeSpan), "00:00", "23:59")]



回答3:


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.



来源:https://stackoverflow.com/questions/18624766/range-and-displayformat-attributes-on-timespan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!