• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 387
  • Last Modified:

Conditional Web Page required field validator

I have a web I inherited

There are two items which I need to link together

First...I can easily add the required field validator for either control but have it for the dropdown list only right now

What I need is that IF dropdown list selected value = "Yes"
THEN
The txtTravelCo_ is required to be filled in


<asp:DropDownList ID="ddlTravelAssign_" runat="server" CssClass="requiredDDL">
  <asp:ListItem Text="-- Select One --" Value=""></asp:ListItem>
  <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
  <asp:ListItem Text="No" Value="No"></asp:ListItem>
</asp:DropDownList>


<asp:TextBox ID="txtTravelCo_" runat="server" ></asp:TextBox>
0
lrbrister
Asked:
lrbrister
  • 2
1 Solution
 
Kyle HamiltonData ScientistCommented:
post your current script, then we can add to it.
0
 
PryratesCommented:
you can do that by using a custom validator what is a little javascript that is executed before a postback is executed - like all client validation methods (like required etc.)

Here is a sample that is pretty much straight forward.
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlTravelAssign_" runat="server" >
        <asp:ListItem Selected="True" Text="--SELECT ONE--" Value=""></asp:ListItem>
        <asp:ListItem Text="YES" Value="Yes"></asp:ListItem>
        <asp:ListItem Text="NO" Value="No"></asp:ListItem>
        </asp:DropDownList>
        <br /><asp:TextBox ID="txtTravelCo_" runat="server" ></asp:TextBox> 
        <asp:CustomValidator id="MyValidator" ClientValidationFunction="MyValidatorFunction" runat="server" ErrorMessage="Please type in a text."></asp:CustomValidator>
        <br /><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>

    <script type="text/javascript">
        function MyValidatorFunction(Source, args) {
            var condidtionControlSource = document.getElementById("<%=ddlTravelAssign_.ClientID%>");
            var controlToValidate = document.getElementById("<%=txtTravelCo_.ClientID%>");
            if (condidtionControlSource.value == "Yes") {
                args.IsValid = (controlToValidate.value.length > 0);
                return;
            }
            args.IsValid = true;
        }
    </script>

Open in new window


Hope that helps :)
0
 
lrbristerAuthor Commented:
Perfect
Thanks
0
 
PryratesCommented:
You are welcome :)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now