使用asp.net验证器验证2个字段中的1个

时间:2010-02-12 09:01:57

标签: asp.net javascript textbox field requiredfieldvalidator

我有一个带有一些文本框的简单表单。这些文本框都有一个RequiredFieldValidator。如果填写了字段1,我需要禁用字段2的RequiredFieldValidator,因为只需要其中一个字段。实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分: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))
}

答案 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>