MVC unobtrusive validation on checkbox not working

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

    I'm unsure why this didn't work for me, but I opted to use your code and do something slightly different.

    On my JavaScript load I add the following, this makes the checkbox fire the unabtrusive validation if, either you select the checkbox and uncheck it. Also, if you submit the form.

    $(function () {
            $(".checkboxonblurenabled").change(function () {
                $('form').validate().element(this);
            });
    });
    

    You also need to add the CSS class to your checkbox, like so.

    @Html.CheckBoxFor(model => model.AgreeToPrivacyPolicy, new { @class = "checkboxonblurenabled"})
    

    So, we now need to hook up the model and put in out class to handle the server side validation (which i'm re-using from above) but changing the unobtrusiveness slightly.

    Here's the customer attribute that extends IClientValidate as in the above example...

    [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"
            };
        }
    }
    

    In your model, object property set the desired attribute notations

     [MustBeTrue(ErrorMessage = "Confirm you have read and agree to our privacy policy")]
        [Display(Name = "Privacy policy")]
        public bool AgreeToPrivacyPolicy { get; set; }
    

    Okay, we're ready to put in the JavaScript.

    (function ($) {
        /*
        START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
        START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
        START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
        */
        jQuery.validator.unobtrusive.adapters.add("mustbetrue", ['maxint'], function (options) {
            options.rules["mustbetrue"] = options.params;
            options.messages["mustbetrue"] = options.message;
        });
    
        jQuery.validator.addMethod("mustbetrue", function (value, element, params) {
    
            if ($(element).is(':checked')) {
                return true;
            }
            else {
                return false;
            }
        });
        /*
        START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
        START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
        START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
        */
    
    
    
    } (jQuery));
    

    What makes this work, is... well. After looking at the HTML markup after trying to do the suggested answer above, my values were all set to true, however my checkbox checked was false. So, I decided to let jQuery work it out using IsChecked

提交回复
热议问题