MVC unobtrusive validation on checkbox not working

后端 未结 6 765
执笔经年
执笔经年 2020-12-04 08:03

I\'m trying to implement the code as mentioned in this post. In other words I\'m trying to implement unobtrusive validation on a terms and conditions checkbox. If the user

6条回答
  •  眼角桃花
    2020-12-04 08:14

    You need to implement IClientValidatable on your custom attribute in order to tie the mustbetrue adapter name that you are registering on the client side with this attribute:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "mustbetrue"
            };
        }
    }
    

    UPDATE:

    Full working example.

    Model:

    public class MyViewModel
    {
        [MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
        [DisplayName("Accept terms and conditions")]
        public bool AcceptsTerms { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel();
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    View:

    @model MyViewModel
    
    
    
    
    
    @using (Html.BeginForm())
    {
        @Html.CheckBoxFor(x => x.AcceptsTerms)
        @Html.LabelFor(x => x.AcceptsTerms)
        @Html.ValidationMessageFor(x => x.AcceptsTerms)
        
    }
    

提交回复
热议问题