A. McKenzie A. McKenzie - 1 month ago 10
Vb.net Question

VB + ASP.net : How to disable requiredfieldvalidator on condition

I want to disable a required field validator for a dropdown list based on the selected value of a separate dropdown list.

<asp:DropDownList runat="server" CssClass="form-control " ID="ddl_Title" ClientIDMode="Static" CausesValidation="false">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Mr</asp:ListItem>
<asp:ListItem>Mrs</asp:ListItem>
<asp:ListItem>Ms</asp:ListItem>
<asp:ListItem>Miss</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
</div>


<div class="row" id="Other">
<div class="col-md-1"></div>
<div class="col-md-2"><asp:DropDownList runat="server" CssClass="form-control " ID="ddl_Other" Width="155"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4"
runat="server"
ControlToValidate="ddl_Other"
ErrorMessage="*Title is required."
Forecolor="Red"
Display="Dynamic"
InitialValue="-1">
</asp:RequiredFieldValidator>
<div class="col-md-9"></div>
</div>
</div>


So the validation control is only enabled when the selected value of the first dropdown list is "Other"

If ddl_Title.SelectedValue Is "Other" Then

RequiredFieldValidator4.Enabled = True

Else

RequiredFieldValidator4.Enabled = False

End If


How do I make this work??

Answer

Add a OnSelectedIndexChanged event to the DropDownList with AutoPostBack set to true.

<asp:DropDownList runat="server" CssClass="form-control " ID="ddl_Title" ClientIDMode="Static" CausesValidation="false" OnSelectedIndexChanged="ddl_Title_SelectedIndexChanged" AutoPostBack="true">

And then in code behind.

Protected Sub ddl_Title_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    If ddl_Title.SelectedValue Is "Other" Then
        RequiredFieldValidator4.Enabled = True
    Else
        RequiredFieldValidator4.Enabled = False
    End If
End Sub