Google Search

Google
 

Tuesday, February 26, 2008

Enable/Disable RequiredFieldValidator with Javascript

Sometimes we need to Enable or Disable validation on client side.For that use ValidatorEnable function in the Asp.net javacsript Script Library.

For that set EnableClientScript property of validator to True.

Here i give example for this:

I have a page with a couple of radio buttons.On radio button selection i want to enable/disable validation.

In example if i select Email radio button then Email div will display and only txtEmail textbox validator is enabled.

Java Script for this:

<script language="JavaScript" type="text/javascript">
function autoSelect(control,type)
{
if(type=="Email")
{
document.getElementById('Email').style.display="block";
document.getElementById('PhoneNo').style.display="none";
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true);
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);

}
else
{
document.getElementById('Email').style.display="none";
document.getElementById('PhoneNo').style.display="block";
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), false);
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), true);
}
}
</script>

Code for this:


Email :
<input type="radio" id="RadioButton1" runat="server" value="Plan1" name="Plan" onclick="autoSelect(this,'Email')" checked />
PhoneNo :
<input type="radio" id="RadioButton2" runat="server" value="Plan1" name="Plan" onclick="autoSelect(this,'PhoneNo')" />
<div id="Email">
Email <asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Email Required"
ControlToValidate="txtEmail" EnableClientScript="true" ValidationGroup="vgSubmit" />
</div>
<div id="PhoneNo" style="display:none">
PhoneNo <asp:TextBox ID="txtPhoneNo" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="PhoneNo Required"
ControlToValidate="txtPhoneNo" EnableClientScript="true" ValidationGroup="vgSubmit"/>
</div>
<asp:Button ID="btnSubmit" runat="server" Text="Button" ValidationGroup="vgSubmit"/>