在ASP.NET中沒有提供的檢驗器允許您執行基於另一個控制條件的驗證。但是,您可以通過使用在客戶端,服務器端或兩者上執行驗證的CustomValidator來實現此目的(建議至少進行服務器端驗證)。驗證器與嚮導一起運行良好。
ASP.NET標記示例:
<asp:DropDownList ID="OptionsDropDownList" runat="server">
<asp:ListItem Text="Website" />
<asp:ListItem Text="Search Engine" />
<asp:ListItem Text="Other" />
</asp:DropDownList>
<asp:TextBox ID="OtherTextBox" runat="server" />
<asp:CustomValidator ID="custvOptionsDropDownList" runat="server" ControlToValidate="OptionsDropDownList"
ValidateEmptyText="true" Display="Dynamic" ClientValidationFunction="validateOtherTextBox"
ErrorMessage="This field is required!" OnServerValidate="ValidateOtherTextBox" />
的JavaScript ClientValidationFunction:
<script type="text/javascript" language="javascript">
function validateOtherTextBox(event, args) {
var textbox = document.getElementById('<%= OtherTextBox.ClientID %>').value;
if (args.Value == 'Other')
args.IsValid = (textbox != '');
else
args.IsValid = true;
}
</script>
代碼隱藏OnServerValidate:
protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args)
{
if (OptionsDropDownList.SelectedValue == "Other")
{
args.IsValid = (OtherTextBox.Text.Trim() != "");
}
}
請注意,您可以選擇實施任何您需要的。您可以完全跳過Javascript驗證並刪除該代碼和ClientValidationFunction
屬性。另外請注意,JavaScript通過使用ClientID屬性引用目標控件。這是必需的,因爲ASP.NET在輸出頁面時分配了不同的ID,並且您希望以這種方式將它提供給Javascript方法(查看頁面上的源代碼,您將看到控件名稱有一個額外的前綴等)。