我需要为国家(下拉列表),地址(文本框),城市(文本框),州(下拉)和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