2
votes

There are a few other posts I've seen about this:

MVC unobtrusive validation on checkbox not working

MVC3: make checkbox required via jQuery validate?

But I've implemented them and can't quite figure out why my validation isn't working properly:

Attribute:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {
        public override bool IsValid(object value) {
            return value != null && (bool)value;
        }

        public override string FormatErrorMessage(string name) {
            return string.Format("The {0} field must be true.", name);
        }

        #region Implementation of IClientValidatable

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            yield return new ModelClientValidationRule {
                ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "mustbetrue"
            };
        }

        #endregion
    }

Adapter extension:

// Unobtrusive validation extras
$.validator.unobtrusive.adapters.addBool("mustbetrue", function (options) {
    //b-required for checkboxes
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

Model property:

    [Display(Name = "I agree to RustyShark's Terms of Use")]
    [MustBeTrueAttribute(ErrorMessage = "You must agree to the Terms of Use")]
    public bool AgreeToTerms { get; set; }

View:

<div class="formField">
    <div class="label">
        @Html.LabelFor(m => m.AgreeToTerms); @Html.ActionLink("view here", "TermsOfUse", "Home", null, new { target = "_blank" }).
    </div>
    <div class="input">
        @Html.CheckBoxFor(m => m.AgreeToTerms)
    </div>
    @Html.ValidationMessageFor(m => m.AgreeToTerms)
</div>

The following HTML is rendered:

<div class="formField">
    <div class="label">
        <label for="AgreeToTerms">I agree to RustyShark's Terms of Use</label>; <a href="/Home/TermsOfUse" target="_blank">view here</a>.
    </div>
    <div class="input">
        <input data-val="true" data-val-mustbetrue="You must agree to the Terms of Use" data-val-required="The I agree to RustyShark&amp;#39;s Terms of Use field is required." id="AgreeToTerms" name="AgreeToTerms" type="checkbox" value="true" class="valid"><input name="AgreeToTerms" type="hidden" value="false">
    </div>
    <span class="field-validation-valid" data-valmsg-for="AgreeToTerms" data-valmsg-replace="true"></span>
</div>

Server side validation is working (although it's returning the default error message, rather than the overridden one), but client side isn't - I'm just not getting any message back, but everything is being executed correctly? Can anyone see my issue?

1

1 Answers

4
votes

Finally figured it out!

The major issue was that I was executing the $.validator methods inside my $(document).ready() function. It needs to be executed as an in-line function! I just moved them outside the ready(), and things started to happen!

Additionally, the JS should read as follows:

$.validator.addMethod("mustbetrue", function (value, element, params) {
    return value == true;
});
$.validator.unobtrusive.adapters.add("mustbetrue", 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;
        }
    }
});