1

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

4

2 回答 2

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))
}
于 2010-02-12T09:10:24.253 回答
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>
于 2010-02-12T09:23:06.453 回答