MVC3: make checkbox required via jQuery validate?

前端 未结 3 1049
[愿得一人]
[愿得一人] 2020-12-04 08:44

I want my \"Agree To Terms\" checkbox to be mandatory using jQuery validate, in an MVC3 project. I currently get server/client DRY/SPOT validation from \"MS data annotation

3条回答
  •  旧时难觅i
    2020-12-04 09:14

    I've summarized here the correctly-working source code, which resulted from applying the accepted answer. Hope you find it useful.

    RequiredCheckbox.aspx

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
    
    
    
    
        RequiredCheckbox
        
        
        
        
    
    
        
    <% // These directives can occur in web.config instead Html.EnableUnobtrusiveJavaScript(); Html.EnableClientValidation(); using (Html.BeginForm()) { %> <%: Html.CheckBoxFor(model => model.IsTermsAccepted)%> <%: Html.ValidationMessageFor(model => model.IsTermsAccepted)%> <%: Html.TextBoxFor(model => model.ContactName)%> <%: Html.ValidationMessageFor(model => model.ContactName)%> <% } %>

    RegistrationViewModel.cs

    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    
    public class RegistrationViewModel {
        [Mandatory (ErrorMessage="You must agree to the Terms to register.")]
        [DisplayName("Terms Accepted")]
        public bool isTermsAccepted { get; set; }
    
        [Required]
        [DisplayName("Contact Name")]
        public string contactName { get; set; }
    }
    

    MandatoryAttribute.cs

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    public class MandatoryAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return (!(value is bool) || (bool)value);
        }
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "mandatory";
            yield return rule;
        }
    }
    

提交回复
热议问题