2010-02-12 102 views
1

我已经有了一些带有文本框的简单表单。这些文本框都有一个RequiredFieldValidator。如果填充字段1,则需要禁用字段2的RequiredFieldValidator,因为只需要其中一个字段。什么是完成这个最好的方法?使用asp.net验证器验证2个字段中的1个

回答

1

目前我用JavaScript解决了它的处理程序,我可以正常使用的验证。

<script language="javascript" type="text/javascript"> 
function CheckPhoneValidator(txtEmail) 
{ 
    var phoneValidator = document.getElementById('<%= ReqPhone.ClientID %>'); 
    ValidatorEnable(phoneValidator, txtEmail.value == '' ? true : false); 
} 

function CheckEmailValidator(txtPhone) 
{ 
    var emailValidator = document.getElementById('<%= ReqEmail.ClientID %>'); 
    var emailRegexValidator = document.getElementById('<%= RegexEmail.ClientID %>'); 
    ValidatorEnable(emailValidator, txtPhone.value == '' ? true : false); 
    ValidatorEnable(emailRegexValidator, txtPhone.value == '' ? true : false); 
} 

而这些控件:

<tr> 
    <td> 
     E-mail adres: 
    </td> 
    <td> 
     <asp:TextBox ID="TxtEmail" runat="server" onchange="javascript:CheckPhoneValidator(this);"></asp:TextBox> 
     <asp:RequiredFieldValidator ID="ReqEmail" runat="server" ControlToValidate="TxtEmail" ErrorMessage="U moet een e-mail invullen als u geen telefoonnummer heeft ingevuld." Display="Dynamic" ValidationGroup="Contact">&nbsp;</asp:RequiredFieldValidator> 
     <asp:RegularExpressionValidator ID="RegexEmail" runat="server" ControlToValidate="TxtEmail" ErrorMessage="Dit is geen geldig e-mail adres." Display="Dynamic" ValidationExpression="([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})" ValidationGroup="Contact">&nbsp;</asp:RegularExpressionValidator> 
    </td> 
</tr> 
<tr> 
    <td> 
     Telefoonnummer: 
    </td> 
    <td> 
     <asp:TextBox ID="TxtPhone" runat="server" onchange="javascript:CheckEmailValidator(this);"></asp:TextBox> 
     <asp:RequiredFieldValidator ID="ReqPhone" runat="server" ControlToValidate="TxtPhone" ErrorMessage="U moet een telefoonnummer invullen als u geen e-mail heeft ingevuld." Display="Dynamic" ValidationGroup="Contact">&nbsp;</asp:RequiredFieldValidator> 
    </td> 
</tr> 
1

在这种情况下,使用CustomValidator与服务器端验证处理程序更简单。你应该自定义验证添加到两个控件:

<asp:TextBox runat="server" id="control1" /> 
<asp:CustomValidator runat="server" id="cusCustom1" controltovalidate="control1" onservervalidate="cusCustom_ServerValidate" errormessage="your message" /> 
<asp:TextBox runat="server" id="control2" /> 
<asp:CustomValidator runat="server" id="cusCustom2" controltovalidate="control2" onservervalidate="cusCustom_ServerValidate" errormessage="your message" /> 

和实施类似

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e) 
{ 
    e.IsValid = (!string.IsNullOrempty(control1.Text)) || (!string.IsNullOrempty(control2.Text)) 
} 
+0

为什么只是服务器端验证处理?为什么不是客户端和服务器端? – rrrr 2010-02-12 09:12:01

+0

当然。 CustomValidator标签可以具有额外的ClientValidationFunction =“customJSValidatingFunction”属性。 – PanJanek 2010-02-12 09:20:11