在我的網頁中,我試圖在客戶端和服務器端進行預先驗證。如果下拉菜單和文本框爲空,我需要顯示一條錯誤消息,但是如果填寫了其中一個,驗證應該通過。 有沒有辦法爲兩個控件創建一個CustomValidator?我有一種感覺,我做得不對。ASP.NET自定義驗證程序客戶端和服務器端驗證
客戶端代碼:
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="ddlStates" runat="server" Width="128px">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Nevada</asp:ListItem>
<asp:ListItem>Uta</asp:ListItem>
<asp:ListItem>Oregon</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:CustomValidator ID="cvddlState" runat="server"
ClientValidationFunction="StatesCheck"
OnServerValidate="ServerValidation"
ErrorMessage="(*) State is required" ForeColor="Red"
Display="Dynamic"></asp:CustomValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtStates" runat="server"></asp:TextBox>
</td>
<td>
<asp:CustomValidator ID="cvtxtStates" runat="server"
ValidateEmptyText="true"
ClientValidationFunction="StatesCheck"
OnServerValidate="ServerValidation"
ControlToValidate="txtStates"
ErrorMessage="(*) Text cannot be empty" ForeColor="Red"
Display="Dynamic"></asp:CustomValidator>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
</div>
<div id="divErrorMessage" runat="server" class="alert alert-danger" visible="false"></div>
<script type="text/javascript">
'Use Strict';
function StatesCheck(source, args) {
var ddlStates = document.getElementById("<%=ddlStates.ClientID%>");
var txt = document.getElementById('<%=txtStates.ClientID%>').value;
var state = ddlStates.options[ddlStates.selectedIndex].value;
if (ddlStates !== null) {
if ((state === "") && (txt === "")) {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
</script>
服務器端代碼:
Public Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
divErrorMessage.Visible = False
divErrorMessage.InnerText = ""
Dim ddlSelection As String = ddlStates.SelectedItem.Text
Dim statesText As String = txtStates.Text.Trim()
If statesText = String.Empty And ddlSelection = String.Empty Then
Else
divErrorMessage.Visible = True
divErrorMessage.InnerText = "(*) Text cannot be empty"
End If
Catch ex As Exception
End Try
End Sub
Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs)
If (ddlStates.SelectedItem.Text = String.Empty) And (txtStates.Text.Length = 0) Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub