如何让jQuery.validate()在带有母版页的ASP.NET中工作?

时间:2014-03-07 09:09:01

标签: jquery asp.net validation jquery-validate

我的表单包含母版页和子页面..

如何验证子页面内的表单?当我尝试使用母版页时,验证不会运行。但是,当我不使用母版页时,一切都有效。

请解释如何让jQuery Validate在带有母版页的ASP.NET中工作。

1 个答案:

答案 0 :(得分:0)

我意识到这有点晚了,但我想我会分享我的发现,因为我刚刚经历过这个。

要在ASP.Net母版页环境中使用jQuery验证,您必须记住占位符更改包括名称在内的所有内容。由于.validate()在很大程度上依赖于每个字段的名称,因此必须获取每个字段的客户端名称。因为这可能会根据您的占位符而变化(我的最终看起来像name="ctl00$ContentPlaceHolder1$FirstName"),您的代码看起来应该是这样的:

$(document).ready(function () {
        $('form').validate({
            rules: {
                <%= FirstName.Name %>: {
                    required: true,
                    minlength: 2,
                    maxlength: 25
                },
                <%= LastName.Name %>: {
                    required: true
                },
                <%= Email1.Name %>: {
                    required: true,
                    email: true
                },
                <%= Email2.Name %>: {
                    required: true,
                    email: true,
                    equalTo: "#<%= Email1.ClientID %>"
                },
                <%= Password1.Name %>: {
                    required: true,
                    minlength: 7
                },
                <%= Password2.Name %>: {
                    required: true,
                    minlength: 7,
                    equalTo: "#<%= Password1.ClientID %>"
                }
            },
            messages:{
                <%= FirstName.Name %>: {
                    required: "Please enter your first name.",
                    minlength: $.validator.format("Your first name must be at least {0} characters.")
                },
                <%= LastName.Name %>: {
                    required: "Please enter your last name.",
                    minlength: $.validator.format("Your last name must be at least {0} characters.")
                },
                <%= Email1.Name %>: {
                    required: "Please enter your email address.",
                    email: "Please enter a valid email address."
                },
                <%= Email2.Name %>: {
                    required: "Please confirm your email address.",
                    email: "Please confirm with a valid email address.",
                    equalTo: "Email entries do not match."
                },
                <%= Password1.Name %>: {
                    required: "Please enter a password",
                    minlength: $.validator.format("Your password must be at least {0} characters.")
                },
                <%= Password2.Name %>: {
                    required: "Please confirm your password.",
                    equalTo: "Passwords do not match."
                }
            },
            errorClass: "error-label",
            wrapper: "li",
            errorLabelContainer: "#ErrorSection"
        });
    });

此代码直接来自我的工作网页,使用jQuery Validation版本1.12.0和jQuery版本1.11.0。

编辑:我应该补充一点,我验证的所有输入也是runat="server",用于服务器端交互。