I have conditional validation that I need to perform. The logic is supposed to work like this:
If radio button 1 is selected, textbox1 is required.
If radio button 2 is selected, dropdownlist1 is required.
What is the best way to accomplish this?
I have conditional validation that I need to perform. The logic is supposed to work like this:
If radio button 1 is selected, textbox1 is required.
If radio button 2 is selected, dropdownlist1 is required.
What is the best way to accomplish this?
Client-side using JQuery validation plugin. Adjust the names to fit those given by ASP.NET if using ASP.NET controls. Server-side is relatively easy - check which radio is selected and make sure that the value of the textbox or dropdown list is non-null.
$(function() {
$('form').validate( {
rules: {
required-textbox: function() { return $('#radio_yes:checked').size(); }
required-ddl: function() { return $('#radio_no:checked').size(); }
}
});
})
<input type='radio' id='radio_yes' name='radio' value='1' /> Choice 1
<input type='radio' id='radio_no' name='radio' value='2' /> Choice 2
<input type='text' id='textinp' name='textinp' class='required-textbox' />
<select id='ddl' name='ddl' class='required-ddl'>
<option ... />
</select>
You could also do this with a CustomValidator -- again using jQuery client-side. Again, the server-side functions are trivial (and basically the same as the other case).
function validateTextBox(source, args)
{
args.IsValid = $('[id$="radio_yes"]:checked').size() && $(source).val();
}
function validateDDL(source, args)
{
args.IsValid = $('[id$="radio_no"]:checked').size() && $(source).val();
}
<asp:RadioButton ID="radio_yes" runat="server" GroupName="radio" /> Choice 1
<asp:RadioButton ID="radio_no" runat="server" GroupName="radio" /> Choice 2
<asp:TextBox ID="textbox" runat="server" />
<asp:CustomValidator ID="textboxValidator" runat="server"
ControlToValidate="textbox"
ClientValidationFunction="validateTextBox"
OnServerValidate="ddl_Validate"
Display="Static"
ErrorMessage="*" />
<asp:DropDownList ID="ddl" runat="server">
....
</asp:DropDownList>
<asp:CustomValidator ID="ddlValidator" runat="server"
ControlToValidate="ddl"
ClientValidationFunction="validateDDL"
OnServerValidate="textbox_Validate"
Display="Static"
ErrorMessage="*" />