0

在我的网络表单上,我有一个文本框,我想对它执行自定义验证:

<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>

在我后面的代码中,我将日期 TextBox 的 Text in 设置为Page_Load,并且我有一个验证功能:

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),则验证函数不会收到我输入的值。相反, insidevalDate_ServerValidateargs.Value设置为在 Page_Load 中设置的文本框的初始值。这里发生了什么?

4

1 回答 1

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
于 2013-08-21T22:22:49.570 回答