本文介绍了asp.net的CustomValidator永远不会触发OnServerValidate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的ASP页:
<asp:Content ID="Content2" ContentPlaceHolderID="ShellContent" runat="server">
<form runat="server" id="AddNewNoteForm" method="post"">
<fieldset id="NoteContainer">
<legend>Add New Note</legend>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<div class="ctrlHolder">
<asp:Label ID="LabelNoteDate" runat="server" Text="Note Date"
AssociatedControlID="NoteDateTextBox"></asp:Label>
<asp:TextBox ID="NoteDateTextBox" runat="server" class="textInput"
CausesValidation="True" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="CustomValidator"
ControlToValidate="NoteDateTextBox"
OnServerValidate="CustomValidator1_ServerValidate"
Display="Dynamic"
>*</asp:CustomValidator>
</div>
<div class="ctrlHolder">
<asp:Label ID="LabelNoteText" AssociatedControlID="NoteTextTextBox" runat="server" Text="Note"></asp:Label>
<asp:TextBox ID="NoteTextTextBox" runat="server" Height="102px"
TextMode="MultiLine" class="textInput" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="Note Text is Required" ControlToValidate="NoteTextTextBox">*</asp:RequiredFieldValidator>
</div>
<div class="buttonHolder">
<asp:Button ID="OkButton" runat="server" Text="Add New Note"
CssClass="primaryAction" onclick="OkButton_Click"/>
<asp:HyperLink ID="HyperLink1" runat="server">Cancel</asp:HyperLink>
</div>
</fieldset>
</form>
</asp:Content>
和背后以下code为CustomValidator1_ServerValidate()方法:
and the following code behind for the CustomValidator1_ServerValidate() method:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(args.Value.Trim()))
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "Note Date is Required!";
return;
}
DateTime testDate;
if (DateTime.TryParse(args.Value, out testDate))
{
args.IsValid = true;
CustomValidator1.ErrorMessage = "Invalid Date!";
}
}
它似乎永远不会失败验证不管是什么我把在文本框中...
It never seems to fail validation no matter what I put in the text box...
应该提到这是ASP.NET 2.0
Should mention this is ASP.NET 2.0
推荐答案
为了使用的CustomValidator,您还需要为同一控制一个RequiredFieldValidator。只要把一个RequiredFieldValidator为NoteDateTextBox,它应该解雇的CustomValidator的服务器事件给你。
In order to use a customvalidator, you also need a requiredfieldvalidator for that same control. Just put a requiredfieldvalidator for NoteDateTextBox and it should fire the customvalidator's server event for you.
这篇关于asp.net的CustomValidator永远不会触发OnServerValidate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!