MVC Adding methods into jquery.validate.unobtrusive.js

前端 未结 3 1139
醉酒成梦
醉酒成梦 2021-02-03 10:17

I recently had a question on getting checkbox validation working on the client side within a MVC project. This question was successfully answered, but raised another query.

3条回答
  •  礼貌的吻别
    2021-02-03 10:59

    Unobtrusive validation is giving me nothing but grief.

    In a very very simple test page, this works:

    $(document).ready(function () {
        jQuery.validator.unobtrusive.adapters.add(
            'mustbetrue', ['properties'], function (options) {
                options.rules['mustbetrue'] = options.params;
                options.messages['mustbetrue'] = options.message;
            }
            );
    
        jQuery.validator.addMethod('mustbetrue', function (value, element, params) {
            // check if dependency is met
            if (!this.depend(param, element)) {
                return "dependency-mismatch";
            }
    
            switch (element.type) {
                case "checkbox":
                    return element.checked;
                    break;
                case "hidden":
                    return (value == 'true' || value == 'True');
                    break;
                default:
                    alert('type = ' + element.type);
                    return true;
                    break;
            }
        });
    });
    

    However, when I move this code to my more complex form, suddenly it stops working and I have no idea why and no time to delve into the unobtrusive code to try and find out.

    counsellorben's solution works in my more complex form.

    If anyone can point me to a site that explains in detail how to properly add a custom validator to unobtrusive validation, I will be forever greatful. Each site I visit has a different solution.

提交回复
热议问题