MVC unobtrusive validation on checkbox not working

后端 未结 6 770
执笔经年
执笔经年 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:20

    ///  
    ///  Summary : -CheckBox for or input type check required validation is not working the root cause and solution as follows
    ///
    ///  Problem :
    ///  The key to this problem lies in interpretation of jQuery validation 'required' rule. I digged a little and find a specific code inside a jquery.validate.unobtrusive.js file:
    ///  adapters.add("required", function (options) {
    ///  if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
    ///    setValidationValues(options, "required", true);
    ///    }
    ///   });
    ///   
    ///  Fix: (Jquery script fix at page level added in to check box required area)
    ///  jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {
    ///   if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
    ///              options.rules["required"] = true;
    ///   if (options.message) {
    ///                   options.messages["required"] = options.message;
    ///                       }
    ///  Fix : (C# Code for MVC validation)
    ///  You can see it inherits from common RequiredAttribute. Moreover it implements IClientValidateable. This is to make assure that rule will be propagated to client side (jQuery validation) as well.
    ///  
    ///  Annotation example :
    ///   [BooleanRequired]
    ///   public bool iAgree { get; set' }
    ///    
    
    /// 
    
    
    public class BooleanRequired : RequiredAttribute, IClientValidatable
    {
    
        public BooleanRequired()
        {
        }
    
        public override bool IsValid(object value)
        {
            return value != null && (bool)value == true;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "brequired", ErrorMessage = this.ErrorMessage } };
        }
    }
    

提交回复
热议问题