我已经使用JQuery插件在.Net表单上设置了验证,所有内容都适用于页面加载,但在回发后,验证停止工作。
然后,如果我清空一个被请求的字段并尝试提交,当我的.Net验证程序捕获问题客户端时,字段上的实时验证将再次开始工作。
这是一个重现问题的小代码示例:
<script language="javascript">
$(document).ready(function () {
ValidateElements();
});
function ValidateElements() {
jQuery.validator.messages.required = " ";
jQuery.validator.messages.email = " ";
var rules = {};
rules[$("#<%=TxtInvoiceName.ClientID%>").attr("name")] = {
required: true
};
$('form').validate({
rules: rules,
success: function (label) {
},
errorPlacement: function (label) {
}
});
$("#MainForm").validate().form();
}
</script>
<style>
input.error {
border: 1px solid red;
}
</style>
<form id="MainForm" runat="server">
<div>
<asp:TextBox runat="server" ID="TxtInvoiceName" Text="" />
<asp:RequiredFieldValidator ID="RequiredFieldInvoiceName" runat="server" ErrorMessage=""
Display="Dynamic" ControlToValidate="TxtInvoiceName"></asp:RequiredFieldValidator>
<asp:Label runat="server" ID="LblTxtInvoiceNameValidate" AssociatedControlID="TxtInvoiceName"> </asp:Label>
<asp:Button runat="server" Text="PostBack" OnClick="PostBack" />
</div>
</form>
希望有人可以指出我做错了什么。
答案 0 :(得分:1)
您只需在页面上添加一个小脚本,以便在回发后替换所有验证规则
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
ValidateElements();
}
这将为下一个表单提交放回验证规则。
答案 1 :(得分:0)
我已经修改了你的ValidateElements函数,试试这个:
function ValidateElements() {
jQuery.validator.messages.required = " ";
jQuery.validator.messages.email = " ";
var rules = {};
rules[$("#<%=TxtInvoiceName.ClientID%>").attr("name")] = {
required: true
};
var $form = $('#MainForm');
$form.validate({
rules: rules,
success: function (label) {
},
errorPlacement: function (label) {
}
});
// whenever an input element's blur event fires,
// revalidate the form. do this because the asp.net
// validators use this behavior
$form.find(':input').blur(function() {
$form.valid();
});
// revalidate the form on submit.
// better approach because it requires less form revalidation
// on the client side, but it won't be in "synch" with the
// asp.net client side validation
// $('#<%= Button1.ClientID %>').click(function() {
// return $form.valid();
// });
}