jQuery验证。添加动态规则和消息

时间:2011-06-23 10:20:32

标签: jquery asp.net jquery-validate

我一直在努力让jQuery验证插件与Asp.Net webforms一起使用,这样我就可以模仿验证组的行为。

我编写的代码基于Dave Wards博客条目here,其中包含一些增强功能,旨在让我自定义为每个组显示的规则和消息。

该过程应该如下工作:

  1. 默认表单行为已更改。

  2. 调用一个使用Ajax的方法 加载到jSON对象 相关的规则/信息 那个小组。

  3. 验证插件的默认值将被覆盖。

  4. 组内的每个元素都是 测试,如果它失败了点击 事件将阻止默认 提交。

  5. 不幸的是,验证测试在组内的每个元素上都返回true。我现在唯一能想到的就是我设置的规则是不正确的。我根据元素的名称使用它的属性名称声明每个规则。这是对的吗?

    e.g。

      

    “ui_txt_Password”:{       “必需”:是的,       “minlength”:5}

    到目前为止我的验证码....对于纯粹数量的道歉,我可以发布一个jsfiddle,如果需要,虽然有很多依赖于其他基于ajax的方法,所以它可能会变得混乱。

    提前致谢!

        var validation = {
    
            selectorExpr: "fieldset.vldgroup",
            validateAndSubmit: function ($validator, event) {
                // Ascend from the button that triggered this click event 
                // until we find a container element flagged with 
                // .vldgroup and store a reference to that element.
                var $group = $(event.currentTarget).closest(validation.selectorExpr),
    
                // The validation id to fetch the rules/messages for.
                    validationId = $group.attr("data-validation-id");
    
                $.when(i18n.getValidationMessages(validationId), resources.getValidationRules(validationId)).then(function (messages, rules) {
    
                    // Set the default valid status.
                    var formIsValid = true,
    
                    // Since jSON doesn't allow functions to be parsed we need to convert any min/max/range data to accept a function.
                        rangeProperties = ["maxlength", "minlength", "rangelength", "range", "max", "min"];
    
                    $.each(rangeProperties, function (key, val) {
    
                        // Loop through the properties and check.
                        // TODO: Should we support Safari 2.0.1 and below?
                        // http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript
                        if (messages.hasOwnProperty(val)) {
    
                            // Create a temporary object with a dynamic property name to
                            // extend messages with.
                            var temp = {};
                            temp[val] = $.validator.format(messages[val]);
    
                            // Extend the messages object.
                            $.extend(messages, temp);
    
                            // Clean up
                            temp = null;
                        }
    
                    });
    
                    // Set the default rules to match the current form.
                    $.validator.setDefaults({
                        messages: messages,
                        rules: rules,
                        errorContainer: $("fieldview[data-validation-id=\"" + validationId + "\"] .vld_summary")
                    });
    
                    log($.validator.defaults);
    
                    // Descending from that .vldgroup element, find any input
                    // elements within it, iterate over them, and run validation on 
                    // each of them.
                    $group.find(":input, :checkbox, :password, select").each(function (key, val) {
    
                        if ($validator.element($(val)) === false) {
    
                            formIsValid = false;
                        }
    
                    });
    
                    // If any fields failed validation, prevent the button's click 
                    // event from triggering form submission.
                    if (formIsValid === false) {
                        event.preventDefault();
                    }
    
                });
    
            },
    
            init: function () {
    
                if ($(validation.selectorExpr).length > 0) {
    
                    // Initialize validation on the entire ASP.NET form.
                    var $validator = $("form").validate({
                        // This prevents validation from running on every
                        // form submission by default.
                        onsubmit: false
                    });
    
                    // Bind the click handlers.
                    // Search for controls marked with the .validtrigger flag 
                    // that are contained anywhere within elements marked as 
                    // validategrp, and wire their click event up.
                    $(document).delegate(validation.selectorExpr + " .vldtrigger", "click", function (event) {
    
                        validation.validateAndSubmit($validator, event);
    
                        // Select any input[type=text] elements within a validation group
                        //  and attach keydown handlers to all of them.
                    }).delegate(validation.selectorExpr + " :text", "keydown", function (event) {
    
                        // We're only interested in the enter key (13).
                        if (event.which === 13) {
    
                            // We want to prevent the default form action regardless.
                            event.preventDefault();
    
                            // Find and store the next input element that comes after the
                            //  one in which the enter key was pressed.
                            var $nextInput = $(this).nextAll(":input:first");
    
                            // If the next input is a submit button, trigger its click event.
                            // Else, focus the next form element as if enter === tab.
                            if ($nextInput.is(":submit")) {
    
                                $nextInput.click();
    
                            }
                            else {
    
                                $nextInput.focus();
    
                            }
                        }
    
                    });
                }
    
            }
        };
    

0 个答案:

没有答案