在我的网络表单上,我有一个TextBox,我想在其上执行自定义验证:
<asp:TextBox ID="tbDate" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:CustomValidator runat="server" ID="valDate" ControlToValidate="tbDate" onServerValidate="valDate_ServerValidate" ValidateEmptyText="true" ></asp:CustomValidator>
在我后面的代码中,我在Page_Load
中设置了TextBox的文本日期,并且我有一个验证函数:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tbDate.Text = DateTime.Today.ToShortDateString
End Sub
Protected Sub valDate_ServerValidate(source As Object, args As ServerValidateEventArgs)
Dim newDate As DateTime
args.IsValid = DateTime.TryParse(args.Value, newDate)
End Sub
问题在于:如果我在文本框中输入一个值并单击“提交”按钮(或按Enter键),则验证功能不会收到我键入的值。相反,在valDate_ServerValidate
内,args.Value
设置为在Page_Load中设置的文本框的初始值。这是怎么回事?
答案 0 :(得分:1)
您总是覆盖该值,因此请更改
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tbDate.Text = DateTime.Today.ToShortDateString
End Sub
到
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then tbDate.Text = DateTime.Today.ToShortDateString
End Sub