【问题标题】:Dynamic JQuery Validation Settings with ASP.Net WebForms使用 ASP.Net WebForms 的动态 JQuery 验证设置
【发布时间】:2012-03-16 17:52:59
【问题描述】:

我有两组输入字段的逻辑组,我需要使用 JQuery Validation 分别进行验证,但是由于我使用的是 ASP.Net WebForms,因此我被限制在页面上只有一个表单标签。

即使我有一个使用来自Dave Ward's blog post 的技术的表单,我也已经实现了验证组。这非常有效。

将验证事件绑定到 ASP.Net 表单如下所示:

$("#aspnetForm").validate({
    onsubmit: false,
    ignore: ":hidden",
    errorClass: 'dynamic-class'
});

我需要根据我是尝试提交(并验证)Form A 还是 Form B。例如。 “Form A”将具有“error-class-a”,“Form B”将具有“error-class-B”。我实际上想使用其他验证设置来执行此操作,例如 errorPlacementerrorElement,但我试图让这个解释保持简单。

有没有一种方法可以注入这种行为而不必破解 JQuery Validation 插件源代码?

【问题讨论】:

标签: asp.net jquery-validate webforms


【解决方案1】:

我首先添加了验证组(根据Dave Ward's blog post),所以我有两个逻辑组。在对 JQuery Validate 文档和源代码进行了很长时间的研究后,我将调查范围缩小到一个函数:showErrors()。每次在可能显示任何错误之前都会调用它,无论它是在表单提交事件还是元素之一的模糊事件上。通过相应地更改设置,可以确保始终为正确的元素使用正确的显示设置。

在下面的代码中,一个验证组设置为在 UL 列表摘要中显示错误,另一个内联并使用不同的 css 类。我已经扩展了 showErrors() 函数,以根据包含错误的元素所在的验证组动态切换错误设置。您可能会更进一步并将设置绑定到验证容器以避免笨拙的 IF 语句,但我使用了下面的简单版本,因为它更好地说明了解决方案。最后,我调用了 defaultShowErrors(),正如人们所期望的那样,它调用了验证框架中的默认函数。

   $("#aspForm").validate({
        onsubmit: false,
        // This prevents validation from running on every
        // form submission by default.

        // Extend the show errors function
        showErrors: function (errorMap, errorList) {

            // here we get the element linked to the error.
            // we then find out which validation group the element in question
            // belongs to and set the correct properties
            if (errorList[0]) {
                var element = errorList[0].element;

                // at the time of calling we configure the settings for the validate form
                if ($(element).parents('.validationGroup').attr("id") == "signup") {
                    this.settings.errorClass = "errorSignUp";
                    this.settings.errorContainer = $("*[id$='uivalidation']");
                    this.settings.errorLabelContainer = $("*[id$='uivalidation'] ul");
                    this.settings.errorElement = "li";
                } else {
                    // these are the defaults
                    this.settings.errorClass = "error";
                    this.settings.errorContainer = $([]);
                    this.settings.errorLabelContainer = $([]);
                    this.settings.errorElement = "label";
                }
            }

            // call the default show errors function after we have hooked up the correct settings
            this.defaultShowErrors();
        }
    });

这正是我想要的,因为这意味着我不必对验证框架进行任何更改。这在下面的完整工作示例中得到了演示,其中我为 JQuery 和 JQuery.Validate 使用 CDN!

完整代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Multiple Form Validation</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    <style type="text/css">
        *
        {
            font-family: Verdana;
            font-size: 96%;
        }
        label
        {
            width: 10em;
            float: left;
        }
        label.errorLogin
        {
            float: none;
            color: blue;
            padding-left: .5em;
            vertical-align: top;
        }
        label.error
        {
            float: none;
            color: red;
            padding-left: .5em;
            vertical-align: top;
        }
        p
        {
            clear: both;
        }
        .submit
        {
            margin-left: 12em;
        }
        em
        {
            font-weight: bold;
            padding-right: 1em;
            vertical-align: top;
        }
    </style>
    <script type="text/javascript">
        $(function () {

            $("#aspForm").validate({
                onsubmit: false,
                // This prevents validation from running on every
                // form submission by default.

                // Extend the show errors function
                showErrors: function (errorMap, errorList) {

                    // here we get the element linked to the error.
                    // we then find out which validation group the element in question
                    // belongs to and set the correct properties
                    if (errorList[0]) {
                        var element = errorList[0].element;

                        // at the time of calling we configure the settings for the validate form
                        if ($(element).parents('.validationGroup').attr("id") == "signup") {
                            this.settings.errorClass = "errorSignUp";
                            this.settings.errorContainer = $("*[id$='uivalidation']");
                            this.settings.errorLabelContainer = $("*[id$='uivalidation'] ul");
                            this.settings.errorElement = "li";
                        } else {
                            // these are the defaults
                            this.settings.errorClass = "error";
                            this.settings.errorContainer = $([]);
                            this.settings.errorLabelContainer = $([]);
                            this.settings.errorElement = "label";
                        }
                    }

                    // call the default show errors function after we have hooked up the correct settings
                    this.defaultShowErrors();
                }
            });

            // Search for controls marked with the causesValidation flag 
            //  that are contained anywhere within elements marked as 
            //  validationGroups, and wire their click event up.
            $('.validationGroup .login').click(ValidateAndSubmit);
            $('.validationGroup .signup').click(ValidateAndSubmit);

            // Select any input[type=text] elements within a validation group
            //  and attach keydown handlers to all of them.
            $('.validationGroup :text').keydown(function (evt) {
                // Only execute validation if the key pressed was enter.
                if (evt.keyCode == 13) {
                    ValidateAndSubmit(evt);
                }
            });
        });

        function ValidateAndSubmit(evt) {

            // Ascend from the button that triggered this click event 
            // until we find a container element flagged with 
            // .validationGroup and store a reference to that element.
            var $group = $(evt.currentTarget).parents('.validationGroup');

            var isValid = true;

            // Descending from that .validationGroup element, find any input
            // elements within it, iterate over them, and run validation on 
            // each of them.
            $group.find(':input').each(function (i, item) {
                if (!$(item).valid())
                    isValid = false;
            });

            // If any fields failed validation, prevent the button's click 
            // event from triggering form submission.
            if (!isValid)
                evt.preventDefault();
        }
    </script>
</head>
<body>
    <form id="aspForm" runat="server">
    <fieldset class="validationGroup" id="login">
        <div id="uivalidation">
            <ul></ul>
        </div>
        <legend>Register</legend>
        <p>
            <asp:Label ID="uiFirstName" runat="server" AssociatedControlID="uxFirstName" Text="First name:"></asp:Label>
            <asp:TextBox ID="uxFirstName" runat="server" CssClass="required"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="uxRegister" runat="server" Text="Register" CssClass="login" />
        </p>
    </fieldset>
    <fieldset class="validationGroup" id="signup">
        <legend>Login</legend>
        <p>
            <asp:Label ID="uiUserName" runat="server" AssociatedControlID="uxUserName" Text="User name:"></asp:Label>
            <asp:TextBox ID="uxUserName" runat="server" CssClass="required"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="uxLogin" runat="server" Text="Login" CssClass="signup" />
        </p>
    </fieldset>
    </form>
</body>
</html>

如果这可以进一步改进,请进入并编辑代码。

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多