Enabling / Disabling Required Field Validator using JavaScript

In our current application there is a requirement in one of the pages that when the an user is requesting for a some information, there are some options like Passport Number, Social Security Number are optional values to be submitted. And the client wanted them to be check boxes, because, the end user may submit more than one values. Here comes the actual trick, when the end user selected any one option, the text box next to that should be required. The UI would be some thing like the below

 Requirement

And the code for that is as mentioned below

<asp:CheckBox ID="cbPassport" runat="server" Text="Passport Number" onclick="disableRFV(1)" />

<
asp:TextBox ID="txtPassportNumber" runat="server"></asp:TextBox> &nbsp;

<asp:RequiredFieldValidator ID="rfvPassport" Enabled="false" Display="Dynamic"
EnableClientScript="true" ControlToValidate="txtPassportNumber"
ErrorMessage="Pl Enter Passport Number" runat="server" ValidationGroup="vgFields">
</
asp:RequiredFieldValidator> <br />

<
asp:CheckBox ID="cbSSN" runat="server" Text="Social Security Number" onclick="disableRFV(2)" />

<
asp:TextBox ID="txtSSN" runat="server"></asp:TextBox>

<
asp:RequiredFieldValidator ID="rfvSSN" Enabled="false" Display="Dynamic"
EnableClientScript="true" ControlToValidate="txtSSN"
ErrorMessage="Pl Enter Passport Number" runat="server" ValidationGroup="vgFields">
</
asp:RequiredFieldValidator> <br />

Here you are missing the javascript function disableRFV(). The code for that is as mentioned below

<script language="javascript">
function
disableRFV(val)
{
var enableControl = event.srcElement.status;
if(val == "1")
ValidatorEnable(document.getElementById('<%= rfvPassport.ClientID %>'), enableControl);
else
ValidatorEnable(document.getElementById('<%= rfvSSN.ClientID %>'), enableControl);
}
</script>

The point to note is the ValidatorEnable function that is provided by ASP.NET Javascript Script library. And one more thing that we have to remember is that, while submitting the Required Field Validator control id, we have to pass the clientid, because these controls would be having the runat=“server” tag.


So final points are..


1) Write code for the checkbox with a onclick event


2) Enable the ClientScript for the RequiredFieldValidator


3) Don't forget to associate all the RequiredFieldValidators with ValidationGroup


Final) Within the JavaScript function invoked by the checkbox onclick, use the ValidatorEnable method to enable or disable the RequiredFieldValidator


 


Hope you got it.. if am missing any .. pl remind me

Comments

Popular posts from this blog

Network Intrusion Detection using Supervised ML technique

Common mistakes by Interviewer

Keep the system active, to avoid the auto lock