【发布时间】:2015-06-28 20:13:43
【问题描述】:
我有一个包含大约 30 个文本框的表格。
每行有 2 个文本框,它们具有相同的前缀但不同的后缀,例如 txtAvg From 和 txtAvg To。
我需要遍历表格并对文本框执行自定义验证:
- 只有整数
- 如果 to 和 from 文本框都填写了,我必须检查 from 文本框中的值是否小于 from 值。
- 在每个文本框中输入的范围是 1-100
我稍后可能需要更多验证。此外,如果填写了 to 文本框,则不需要 from,反之亦然。不需要文本框。
我需要进行服务器端验证。
我应该添加自定义验证控件吗?如果是,那么对于每个文本框?
我是否设置controltovalidate?
单击提交按钮时,我需要在每行旁边显示正确的错误。显然,如果页面无效,则不要做任何进一步的事情。
我不想添加不同的验证控件。只有一个自定义验证器。 我还需要动态执行此操作,当用户单击提交按钮时,我希望进行验证并在错误行旁边显示 (*),并在验证摘要中显示完整的错误消息。
我尝试添加控件,但单击按钮时它没有被触发。
Private Sub AddCustomValidation(ByVal container As Control)
Dim custom As CustomValidator
Dim vldtxt As TextBox
For Each ctrl In container.Controls
If TypeOf ctrl Is TextBox Then
vldtxt = CType(ctrl, TextBox)
custom = New CustomValidator
custom.Text = "To field must be bigger than from field"
custom.ControlToValidate = vldtxt.ID
AddHandler custom.ServerValidate, AddressOf CustomValidation
' custom.ServerValidate += New System.Web.UI.WebControls.ServerValidateEventHandler(customvalidation)
Me.form1.Controls.Add(custom)
Else
AddCustomValidation(ctrl)
End If
Next
End Sub
Protected Sub CustomValidation(ByVal source As System.Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim vldtxt As TextBox
Dim othertxt As TextBox
Dim othertxtid As String
Dim txtid As String
Dim lower As String
Dim higher As String
For Each ctrl As Control In tbl1.Controls
vldtxt = TryCast(ctrl, TextBox)
othertxt = TryCast(ctrl, TextBox)
If vldtxt IsNot Nothing Then
txtid = ctrl.ID
''check if to is not empty and if not empty then check that that to value is higher
''than from value
If ((txtid.ToLower.EndsWith("to")) And (vldtxt.Text <> "")) Then
higher = (vldtxt.Text)
othertxtid = vldtxt.ID.Replace("To", "From")
othertxt = Page.FindControl(othertxtid)
othertxt.ID = othertxtid
lower = (othertxt.Text)
If lower = String.Empty Or higher = String.Empty Then
args.IsValid = True
End If
If Int32.Parse(lower) >= Int32.Parse(higher) Then
args.IsValid = False
End If
Else
args.IsValid = True
End If
End If
Next
End Sub
布局是这样的:
<table id="tbl1" runat="server" cellpadding="0" cellspacing="3">
<tr>
<td>From price</td>
<td>
<asp:TextBox runat="server" ID="txtPriceFrom">
</td>
<td>To price</td>
<td>
<asp:TextBox runat="server" ID="txtPriceTo">
</td>
<td>From yield</td>
<td>
<asp:TextBox runat="server" ID="txtYieldFrom">
</td>
<td>To yield</td>
<td>
<asp:TextBox runat="server" ID="txtYieldTo">
</td>
</tr>
</table>
【问题讨论】:
-
你应该自己做作业:P
-
这不是家庭作业。我真的需要帮助。