我以前遇到这个问题,但从来没有解决过。我有一个表单与几个验证器和一个CustomValidator。
<asp:Label ID="lblMemberNum" runat="server" Text="Membership #:" CssClass="LabelMedium" ></asp:Label> <asp:TextBox ID="txtMemberNum" runat="server" CssClass="TextBox" ></asp:TextBox> <asp:requiredFieldValidator ID="rfvMemberNum" SetFocusOnError="True" runat="server" ControlToValidate="txtMemberNum" ErrorMessage="[ Membership # ] is required" CssClass="ValidationMessage" Display="Dynamic" >*</asp:requiredFieldValidator> <asp:RegularExpressionValidator ID="revMemberNum" Display="Dynamic" runat="server" ControlToValidate="txtMemberNum" CssClass="ValidationMessage" ErrorMessage="[ Membership # ] can only contain letters" ValidationExpression="^([a-zA-Z\d]+)$" >*</asp:RegularExpressionValidator> <asp:CustomValidator ID="cvMemberNum" runat="server" CssClass="ValidationMessage" Display="Dynamic" ControlToValidate="txtMemberNum" ValidateEmptyText="false" OnServerValidate="cvMemberNum_Validate" ErrorMessage="This membership number is already registered">*</asp:CustomValidator> <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="ValidationMessage" ShowMessageBox="True" ShowSummary="False" />
在服务器端:
protected void cvMemberNum_Validate(object source,ServerValidateEventArgs args) { try { args.IsValid = (!CampaignRegistration.IsMemberRegistered(args.Value)); } catch { args.IsValid = false; } }
我的问题是:ValidationSummary从未显示CustomValidator的消息。这个问题在几个地方被问到,但我没有看到令人满意的答案。
解决方法
尝试在所有验证器和ValidationSummary之间使用ValidationGroup属性。
编辑:另一种可能是服务器验证码
args.IsValid = (!CampaignRegistration.IsMemberRegistered(args.Value));
如果CampaignRegistration.IsMemberRegistered(args.Value)返回false,“!”使它成真,因此使其有效。我想你应该摆脱“!”如下:
args.IsValid = CampaignRegistration.IsMemberRegistered(args.Value);
更新:为了使ValidationSummary在消息框中显示您的自定义验证器消息,您需要具有ClientValidationFunction代码。如果您只需显示摘要而不显示弹出窗口,则不需要。
<asp:CustomValidator ID="cvMemberNum" runat="server" CssClass="ValidationMessage" Display="Dynamic" ControlToValidate="txtMemberNum" ValidateEmptyText="false" OnServerValidate="cvMemberNum_Validate" ClientValidationFunction = "ClientValidate" ErrorMessage="This membership number is already registered">*</asp:CustomValidator> //JavaScript Code. function ClientValidate(source,args) { args.IsValid = false; //you need to add validation logic here }
更多:如果您不想做ClientSide验证,请尝试此技巧来显示警报。对您的CustomValidator ServerValidate方法进行此更改:
protected void cvMemberNum_Validate(object source,ServerValidateEventArgs args) { bool isValid = true; try { isValid = (!CampaignRegistration.IsMemberRegistered(args.Value)); } catch { isValid = false; } args.IsValid = isValid; if(!isValid) { if(!Page.IsClientScriptBlockRegistered("CustomValidation")) Page.RegisterClientScriptBlock("CustomValidation","<script>alert('This membership number is already registered');</script>"); } }