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

后端 未结 3 1359
野性不改
野性不改 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:35

    In your view model try this

        [Display(Name = "Start Time")]
        [Time]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
        public DateTime Time { get; set; }
    

    and have the attribute class

    public class TimeAttribute : ValidationAttribute, IClientValidatable
    {
        public IEnumerable GetClientValidationRules(ModelMetadata metadata,
                                                                            ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "time"
            };
        }
    
        public override bool IsValid(object value)
        {
            DateTime time;
            if (value == null || !DateTime.TryParse(value.ToString(), out time))
                return false;
    
            return true;
        }
    }
    

    EDIT: I'm also aware that in some cases you need to add some scripting to the client html such as that found in this answer MVC3 unobtrusive validation group of inputs although I'm not exactly sure when its necessary. This answer should get you half way there. Unfortunately, I'm not sure this answer prevents the postback, but it does flag the model as invalid.

提交回复
热议问题