Reputation: 263
I've got a simple form with some textboxes. These textboxes all have a RequiredFieldValidator. If field 1 is filled in I need to disable the RequiredFieldValidator of field 2 because only one of these fields is required. What is the best way to accomplish this?
Upvotes: 1
Views: 1527
Reputation: 263
Currently I've solved it with javascript and I can use normal validators.
<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);
}
And these are the controls:
<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"> </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"> </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"> </asp:RequiredFieldValidator>
</td>
</tr>
Upvotes: 1
Reputation: 6685
In this situation it's simpler to use CustomValidator with server side validating handler. You should add the custom validator to both controls:
<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" />
and implement the handler like
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = (!string.IsNullOrempty(control1.Text)) || (!string.IsNullOrempty(control2.Text))
}
Upvotes: 1