首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JQuery WebForms的动态ASP.Net验证设置

使用JQuery WebForms的动态ASP.Net验证设置
EN

Stack Overflow用户
提问于 2012-03-16 17:52:59
回答 1查看 3K关注 0票数 2

我有两个逻辑组的输入字段,我需要使用JQuery验证分别进行验证,但是,由于我使用的是ASP.Net WebForms,所以只能在页面上使用一个表单标记。

我已经实现了验证组,尽管我使用戴夫·沃德的博客文章中的以下技术实现了一种表单。这工作得很好。

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

代码语言:javascript
复制
$("#aspnetForm").validate({
    onsubmit: false,
    ignore: ":hidden",
    errorClass: 'dynamic-class'
});

我需要更进一步,根据我是试图提交(和验证)表单A还是表单B,有一个不同的errorClass值。“表格A”有“错误级-a”,“表格B”有“错误级-B”。实际上,我希望通过其他验证设置(如errorPlacement和errorElement )来完成此操作,但我尝试将此解释保持简单。

有没有一种方法,我可以注入这种行为,而不必黑客在JQuery验证插件源代码?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-18 00:12:49

我从添加验证组开始(按照戴夫·沃德的博客文章),所以我有两个逻辑组。在对JQuery验证文档和源代码进行了很长时间的研究之后,我将研究范围缩小到一个函数: showErrors()。无论是在表单提交事件上,还是在其中一个元素的模糊事件上,都会在任何错误被显示之前每次调用它。通过相应地更改设置,这将确保正确的显示设置始终用于正确的元素。

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

代码语言:javascript
复制
   $("#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!

全码

代码语言:javascript
复制
<!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>

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9742150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档