我需要爲國家(下拉列表),地址(文本框),城市(文本框),州(下拉)和Zip(文本框)。如果從下拉列表中選擇「美國」,我只想驗證城市,州和郵政編碼。通過「驗證」我的意思是檢查長度 - 就是這樣。如果選擇「美國」作爲國家,只驗證城市,州和郵編
我試過使用自定義驗證器,但我失去了一些東西,因爲看起來應該工作的代碼沒有做任何事情。例如:
<asp:CustomValidator ErrorMessage="City, State, and Zip are required fields"
Display="None" ID="LocationValidator"
runat="server" ClientValidationFunction="validateLocation"
onservervalidate="LocationValidator_ServerValidate">
</asp:CustomValidator>
那麼這裏就是我的驗證碼
客戶端驗證:
function validateLocation(sender, args) {
var country = jQuery("#main_2_MailingAddress_Country").val();
var city = jQuery("#main_2_MailingAddress_City").val();
if (city.Length() > 0)
{
args.IsValid = true;
}
else
{
args.IsValid = country != "United States";
}
}
服務器端驗證:
protected void LocationValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (City.Text.Length > 0)
{
args.IsValid = true;
}
else //nothing was entered for "City"
{
args.IsValid = Country.SelectedValue != "United States";
}
//similar functions for State and Zip go here
}
如果我只做服務器de驗證,並且不填寫表單中的任何內容(除地址字段外還有其他必填字段),那麼我爲其他字段的RequiredFieldValidators激發。但是,如果我填寫除City,State和Zip(選擇美國爲該國家/地區)以外的所有字段,則表單提交時不會捕獲這些空白。
如果我爲自定義驗證器指定了客戶端和服務器端驗證(如上例所示),則不會激發任何驗證器並提交表單。
我意識到這可能是一個漫長而令人困惑的帖子,但是有沒有關於我要去哪裏的錯誤的想法?
您可以在回發時使用Page.Validate()強制進行頁面驗證。 – 2011-01-28 22:25:35