在 ASP.NET 控件上使用 ajax/jQuery 表单验证

Posted

技术标签:

【中文标题】在 ASP.NET 控件上使用 ajax/jQuery 表单验证【英文标题】:Using ajax/jQuery Form Validation on ASP.NET controls 【发布时间】:2013-02-18 05:28:28 【问题描述】:

美好的一天

我正在使用带有母版页的 ASP.NET 页面。我想对输入字段()进行实时表单验证。现在我看到的所有 tuts 和演示/插件都使用普通的 html 标签。我试图在我的表单上实现其中的一些,但它们不起作用。 (我使用的是母版页面和普通的 aspx 网页表单...)

更新:用密码字段的 asp 控件替换输入标签的问题...

原始输入元素

  <fieldset>
        <legend>Validating a complete form</legend>
        <p>
            <label for="firstname">Firstname</label>
            <input id="firstname" name="firstname" type="text" />
        </p>
        <p>
            <label for="lastname">Lastname</label>
            <input id="lastname" name="lastname" type="text" />
        </p>
        <p>
            <label for="username">Username</label>
            <input id="username" name="username" type="text" />
        </p>
        <p>
            <label for="password">Password</label>
            <input id="password" name="password" type="password" />
        </p>
        <p>
            <label for="confirm_password">Confirm password</label>
            <input id="confirm_password" name="confirm_password" type="password" />
        </p>
        <p>
            <label for="email">Email</label>
            <input id="email" name="email" type="email" />
        </p>
        <p>
            <label for="agree">Please agree to our policy</label>
            <input type="checkbox" class="checkbox" id="agree" name="agree" />
        </p>
        <p>
            <label for="newsletter">I'd like to receive the newsletter</label>
            <input type="checkbox" class="checkbox" id="newsletter" name="newsletter" />
        </p>

        <tr>
            <td class="tdRight"><asp:Label ID="LabelEmail" runat="server" Text="Email Address (to be used as username):"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="email" type="email" ID="TextBoxEmail" runat="server" ClientIDMode="Static" TextMode="SingleLine" MaxLength="50"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="tdRight"><asp:Label ID="Label1" runat="server" Text="Postal Address:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox ID="TextBoxPostal" runat="server" ClientIDMode="Static" TextMode="MultiLine" Rows="4" MaxLength="250"></asp:TextBox></td>
        </tr>

        <tr>
            <td class="tdRight"><asp:Label ID="LabelPassword" runat="server" Text="Password:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="password" type="password" ID="TextBoxPassword" runat="server" ClientIDMode="Static" TextMode="Password" MaxLength="50"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="tdRight"><asp:Label ID="LabelConfirmPassword" runat="server" Text="Confirm Password:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="confirm_password" type="password" ID="TextBoxConfirmPassword" runat="server" ClientIDMode="Static" TextMode="Password" MaxLength="50"></asp:TextBox></td>
        </tr>

</fieldset>

我想用下面的 ASP 控件替换上面的内容

        <tr>
            <td class="tdRight"><asp:Label ID="LabelEmail" runat="server" Text="Email Address (to be used as username):"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="email" type="email" ID="TextBoxEmail" runat="server" ClientIDMode="Static" TextMode="SingleLine" MaxLength="50"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="tdRight"><asp:Label ID="Label1" runat="server" Text="Postal Address:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox ID="TextBoxPostal" runat="server" ClientIDMode="Static" TextMode="MultiLine" Rows="4" MaxLength="250"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="tdRight"><asp:Label ID="LabelPassword" runat="server" Text="Password:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="password" type="password" ID="TextBoxPassword" runat="server" ClientIDMode="Static" TextMode="Password" MaxLength="50"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="tdRight"><asp:Label ID="LabelConfirmPassword" runat="server" Text="Confirm Password:"></asp:Label></td>
            <td class="tdLeft"><asp:TextBox name="confirm_password" type="password" ID="TextBoxConfirmPassword" runat="server" ClientIDMode="Static" TextMode="Password" MaxLength="50"></asp:TextBox></td>
        </tr>

现在一切正常,除了密码字段?为什么?此外,ID 并不重要,因为验证器处理名称和类型字段...

jQuery:

 <script type="text/javascript">
        $.validator.setDefaults(
            submitHandler: function ()  alert("submitted!"); 
        );

        $().ready(function () 


            // validate signup form on keyup and submit
            $("form").validate(
                rules: 
                    firstname: "required",
                    lastname: "required",
                    username: 
                        required: true,
                        minlength: 2
                    ,
                    password: 
                        required: true,
                        minlength: 5
                    ,
                    confirm_password: 
                        required: true,
                        minlength: 5,
                        equalTo: "#password"
                    ,
                    email: 
                        required: true,
                        email: true
                    ,
                    topic: 
                        required: "#newsletter:checked",
                        minlength: 2
                    ,
                    agree: "required"
                ,
                messages: 
                    firstname: "Please enter your firstname",
                    lastname: "Please enter your lastname",
                    username: 
                        required: "Please enter a username",
                        minlength: "Your username must consist of at least 2 characters"
                    ,
                    password: 
                        required: "Please provide a password",
                        minlength: "Your password must be at least 5 characters long"
                    ,
                    confirm_password: 
                        required: "Please provide a password",
                        minlength: "Your password must be at least 5 characters long",
                        equalTo: "Please enter the same password as above"
                    ,
                    email: "Please enter a valid email address",
                    agree: "Please accept our policy"
                
            );

            // propose username by combining first- and lastname
            $("#username").focus(function () 
                var firstname = $("#firstname").val();
                var lastname = $("#lastname").val();
                if (firstname && lastname && !this.value) 
                    this.value = firstname + "." + lastname;
                
            );

            //code to hide topic selection, disable for demo
            var newsletter = $("#newsletter");
            // newsletter topics are optional, hide at first
            var inital = newsletter.is(":checked");
            var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
            var topicInputs = topics.find("input").attr("disabled", !inital);
            // show when newsletter is checked
            newsletter.click(function () 
                topics[this.checked ? "removeClass" : "addClass"]("gray");
                topicInputs.attr("disabled", !this.checked);
            );
        );
    </script>

真实渲染的 HTML(与表单有关)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
    $.validator.setDefaults(
        submitHandler: function() 
            alert("submitted!");
        
    );

    $().ready(function() 


        // validate signup form on keyup and submit
        $("form").validate(
            rules: 
                firstname: "required",
                lastname: "required",
                username: 
                    required: true,
                    minlength: 2
                ,
                password: 
                    required: true,
                    minlength: 5
                ,
                confirm_password: 
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                ,
                email: 
                    required: true,
                    email: true
                ,
                topic: 
                    required: "#newsletter:checked",
                    minlength: 2
                ,
                agree: "required"
            ,
            messages: 
                firstname: "Please enter your firstname",
                lastname: "Please enter your lastname",
                username: 
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                ,
                password: 
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                ,
                confirm_password: 
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    equalTo: "Please enter the same password as above"
                ,
                email: "Please enter a valid email address",
                agree: "Please accept our policy"
            
        );

        // propose username by combining first- and lastname
        $("#username").focus(function() 
            var firstname = $("#firstname").val();
            var lastname = $("#lastname").val();
            if (firstname && lastname && !this.value) 
                this.value = firstname + "." + lastname;
            
        );

        //code to hide topic selection, disable for demo
        var newsletter = $("#newsletter");
        // newsletter topics are optional, hide at first
        var inital = newsletter.is(":checked");
        var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
        var topicInputs = topics.find("input").attr("disabled", !inital);
        // show when newsletter is checked
        newsletter.click(function() 
            topics[this.checked ? "removeClass" : "addClass"]("gray");
            topicInputs.attr("disabled", !this.checked);
        );
    );
</script>
<form method="get" action="SignupPersonal.aspx" id="aspnetForm"
class="cmxform">
    <div class="aspNetHidden">
        <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTIwMjk5MTc4MzEPZBYCZg9kFgICBQ9kFgICAQ9kFgICMA8QDxYGHg1EYXRhVGV4dEZpZWxkBQ9FbnVtRGVzY3JpcHRpb24eDkRhdGFWYWx1ZUZpZWxkBQlFbnVtVmFsdWUeC18hRGF0YUJvdW5kZ2QQFQMFRW1haWwlTm90aWZpY2F0aW9uIHZpYSBNb2JpbGUgVGV4dCBNZXNzYWdlcwRCb3RoFQMBMAExATIUKwMDZ2dnZGRksmDjLifKF4+hMs8AhfX/bwcgvt2QqQRuZWngXcH7AGM="
        />
    </div>
    <div class="aspNetHidden">
        <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdABBfr2cGXQNKgk5u/suiS/eBMBPtPHD3IbRvk+yxeYb2457gKW6aCQ3yNBTG9LyKZ4cubOXF5tOYlsiIBcyrDbyQ4wKHhHIVKN2DCQeFUhf9fWAUCuZOob8WzLZCHNXad+6lH/vCaPfCLoThuEr+9Jzl6wAt6cuJ+L+27/Nrmm6upAz//swWW9Bijj8L66VLU8Xqa57A90pLu4vVlIQKRMNCPMnVTRV7QuT7xghzXApY9g0EIzfFocd5Qmeb8RCzKLnYNu/sHr3w5Hv9l1IOx6mNGOqE5LWQWcaFAwIxNHVtD2pkSrWzz9gkUQepnHOZG7M83cV/FFqhRADq7X7PITxLg4JwtYX8Yw9N8ZivtSz9f1K3117QXOtSn4MTHtKkNBE="
        />
    </div>
    <div id="signupPersonal">
        <table>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelName">Name:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxName" type="text" maxlength="50"
                    id="TextBoxName" name="firstname" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelSurname">Surname:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxSurname" type="text" maxlength="50"
                    id="TextBoxSurname" class="required" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelPin">Preferred Pin:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxPin" type="password" maxlength="10"
                    id="TextBoxPin" class="required" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelConfirmPin">Confirm Pin:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxConfirmPin" type="password"
                    maxlength="10" id="TextBoxConfirmPin" class="required" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelPhoneNo">Home Number:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxPhoneNo" type="text" maxlength="20"
                    id="TextBoxPhoneNo" class="required digits" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelMobileNo">Cell Number:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxMobileNo" type="text" maxlength="20"
                    id="TextBoxMobileNo" class="required digits" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelIDNumber">ID Number:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxIDNumber" type="text" maxlength="20"
                    id="TextBoxIDNumber" class="required digits" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelEmail">Email Address (to be used as username):</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxEmail" maxlength="50" id="TextBoxEmail"
                    name="email" type="email" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_Label1">Postal Address:</span>

                </td>
                <td class="tdLeft">
                    <textarea name="ctl00$ContentPlaceHolder1$TextBoxPostal" rows="4" cols="20"
                    id="TextBoxPostal"></textarea>
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelPassword">Password:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxPassword" maxlength="50"
                    id="TextBoxPassword" name="password" type="password" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelConfirmPassword">Confirm Password:</span>

                </td>
                <td class="tdLeft">
                    <input name="ctl00$ContentPlaceHolder1$TextBoxConfirmPassword" maxlength="50"
                    id="TextBoxConfirmPassword" name="confirm_password" type="password" />
                </td>
            </tr>
            <tr>
                <td class="tdRight"><span id="ctl00_ContentPlaceHolder1_LabelContactMethod">Preferred method of contact:</span>

                </td>
                <td class="tdLeft">
                    <select name="ctl00$ContentPlaceHolder1$DropDownListContactMethod" id="DropDownListContactMethod">
                        <option value="0">Email</option>
                        <option value="1">Notification via Mobile Text Messages</option>
                        <option value="2">Both</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" name="ctl00$ContentPlaceHolder1$ButtonRegister" value="Register"
                    id="ctl00_ContentPlaceHolder1_ButtonRegister" class="register" class="submit"
                    type="submit" />
                </td>
            </tr>
        </table>
    </div>
</form>

【问题讨论】:

你能展示一下这个 validate() 函数吗? 好的,会更新我的答案... 究竟什么不能使用密码字段? 验证。没有验证。当您单击 密码字段并输入一个数字或其他内容时,表单会告诉您密码长度太短等。但是在 ASP 密码控件上实现它时,它不起作用 - 所以您可以在那里输入任何内容,甚至什么都没有,并且它不会验证。但困扰我的是,这只发生在密码 asp 控件上,而不是其他的(电子邮件等) 有趣。您可以为表单包含生成的 html 吗?我想知道 ASP.NET 是否对密码字段做了一些奇怪的事情。 【参考方案1】:

除非您的&lt;form&gt; 中的id 不是您想的那样(查看您呈现的代码以验证这一点),否则您的表单验证代码应该可以工作。

您的代码的工作演示:http://jsfiddle.net/b3QNY/

jQuery

$(document).ready(function () 

    $('#form1').validate();

);

HTML

<form id="form1">
    <fieldset>
        <legend>A simple comment form with submit validation and default messages</legend>
        <p>
            <label for="cname">Name</label>
<em>*</em>
            <input id="cname" name="name" size="25" class="required"
            minlength="2" />
        </p>
        <p>
            <label for="cemail">E-Mail</label>
<em>*</em>
            <input id="cemail" name="email" size="25" class="required email"
            />
        </p>
        <p>
            <label for="curl">URL</label>
<em> </em>
            <input id="curl" name="url" size="25" class="url"
            value="" />
        </p>
        <p>
            <label for="comment">Your comment</label>
<em>*</em>
            <textarea id="ccomment" name="comment" cols="22"
            class="required"></textarea>
        </p>
        <p>
            <input class="submit" type="submit" value="Submit" />
        </p>
    </fieldset>
</form>

【讨论】:

谢谢 Sparky,但表单验证仅在我使用 $('form') 而不是表单 ID 时才有效...而且我检查并重新检查了我的 ID...而且,我似乎不能在那里获得密码验证。那里有什么帮助吗?我正在使用github.com/jzaefferer/jquery-validation - 我用我的asp控件替换了所有html控件,但只有密码一个不起作用...... @DavidVanStaden,我在您的 OP 中没有看到任何关于 password 的信息。至于id.validate() 只需要一个有效的jQuery 选择器来初始化表单。如果您的id 不起作用,那么它一定不正确。您是否在 rendered HTML 中查看表单的id?正如您在我的 jsFiddle 演示中看到的那样,您的代码应该可以工作。 我会更新我的答案,除了密码验证器之外,我已经完成了所有工作。出于某种原因,当将 传递给 asp:textbox 时,它不起作用,但它适用于所有其他元素,例如电子邮件……这是为什么呢? @DavidVanStaden,我在里面看不到id,但你已经在equalTo 规则中使用id 来定位它。 @DavidVanStaden,如前所述,JavaScript/jQuery 只查看client-side 代码。换句话说,对 jQuery 来说重要的是 rendered HTML 代码。 如果您使用 jQuery 来定位某些东西,那么目标选择器必须存在于浏览器中呈现的 HTML 中。【参考方案2】:

我想我解决了 - 您必须为密码文本框创建自定义规则...由于某种原因,asp 密码文本框的呈现效果不太好:

                <%= TextBoxPassword.UniqueID %>: 
                     required: true,
                     minlength: 5

                 ,

                <%= TextBoxConfirmPassword.UniqueID %>: 
                    required: true,
                    minlength: 5,
                    equalTo: "#TextBoxPassword"
                ,

表单验证现在可以工作了,除了 Visual Studio 的抱怨 - 它以红色突出显示 : 并说:

“预期的标识符、字符串或数字”

会有问题吗?

【讨论】:

以上是关于在 ASP.NET 控件上使用 ajax/jQuery 表单验证的主要内容,如果未能解决你的问题,请参考以下文章

在 asp.net 控件上动态禁用验证

如何在 reportviewer 控件上从 asp.net 调用打印?

如何在 ASP.NET 页面上注册自定义服务器控件

ASP.Net 过度使用用户控件

使用 ASP.NET 中的 PartialCaching 因控件属性而异

在asp.net服务器控件上的Select2?