Link to home
Start Free TrialLog in
Avatar of FrankG77
FrankG77

asked on

Forcing validators to only trigger upon submit using JQuery.

I have 3 radiobuttons; two have a corresponding textbox, and the last one has a fileupload. The two textboxes and fileupload have a total of 3 separate validators. When a radiobutton is selected, the other two textboxes/fileupload hide, so only one is shown at a time depending on what radiobutton is selected.

I've coded this so if you click a submit button, the only validator that matters is the one that's associated with the selected radiobutton, since I don't want the hidden forms to count. The issue I have is when you select a radio button, the validator error message immediately appears. I only want the error message to appear if the user clicks the submit button without filling out the textbox/fileupload that has been selected.

<asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" runat="server">
    <style type="text/css">
        .singlefield {
            margin-left: 12px;
            padding-right: 12px;
        }

        .radioButtonList label {
            display: inline;
        }

        .Hidden {
            display: none;
        }

        .Invisible {
            visibility: hidden;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <div class="page-content">
        <div class="page-header">
            <h1>Create Campaign
            </h1>
        </div>
        <!-- /.page-header -->
        <div class="row">
            <div class="col-xs-12">
                <!-- PAGE CONTENT BEGINS -->

                <div class="control-group">
                    <label class="control-label bolder blue">What type of message is this?</label>

                    <div class="radio">
                        <label>
                            <input name="form-field-radio" type="radio" class="ace" checked="checked" />
                            <span class="lbl">Simple</span>
                        </label>
                    </div>

                    <div class="radio">
                        <label>
                            <input name="form-field-radio" type="radio" class="ace" />
                            <span class="lbl">Advanced</span>
                        </label>
                    </div>
                </div>

                <br />

                <div class="form-row">
                    <div class="form-group col-md-2">
                        <div class="control-group">
                            <label>
                                <input id="TTSRB" name="form-field-radio2" type="radio" class="ace" checked="checked" />
                                <span class="lbl">Text to Speech</span>
                            </label>
                        </div>
                    </div>
                    <div id="TTS" class="form-group col-md-10">
                        <asp:TextBox ID="TTSTextBox" CssClass="form-control" runat="server"></asp:TextBox>
                        <div class="help-block">
                            <asp:RequiredFieldValidator CssClass="text-danger" ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ErrorMessage="Required." ControlToValidate="TTSTextBox">Required.</asp:RequiredFieldValidator>
                        </div>
                    </div>
                </div>



                <div class="form-row">
                    <div class="form-group col-md-2">
                        <div class="control-group">
                            <label>
                                <input id="RecordPhoneRB" name="form-field-radio2" type="radio" class="ace" />
                                <span class="lbl">Record Using Phone</span>
                            </label>
                        </div>
                    </div>

                    <div id="RecordPhone" class="form-group col-md-10 Invisible">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="icon-phone"></i>
                            </span>
                            <asp:TextBox ID="TextBox1" runat="server" CssClass="form-control input-mask-phone"></asp:TextBox>

                            <span class="input-group-btn">
                                <asp:Button runat="server" ID="cmdCall" Text="Call" CssClass="btn btn-primary btn-sm" />
                            </span>



                        </div>
                    </div>
                    <div class="form-group col-md-2">
                    </div>

                    <div class="form-group col-md-10">
                        <div class="help-block">
                            <asp:RequiredFieldValidator CssClass="text-danger" ID="RequiredFieldValidator2" runat="server" Display="Dynamic" ErrorMessage="Required." ControlToValidate="TextBox1">Required.</asp:RequiredFieldValidator>
                        </div>

                    </div>

                </div>

                <div class="form-row">
                    <div class="form-group col-md-2">
                        <div class="control-group">
                            <label>
                                <input id="UploadFileRB" name="form-field-radio2" type="radio" class="ace" />
                                <span class="lbl">Upload Audio File</span>
                            </label>
                        </div>
                    </div>

                    <div id="UploadFile" class="form-group col-md-10 Invisible">
                        <asp:FileUpload ID="txtFileUpload3" runat="server" />
                        <div class="help-block">
                            <asp:RequiredFieldValidator CssClass="text-danger" ID="RequiredFieldValidator3" runat="server" Display="Dynamic" ErrorMessage="Required." ControlToValidate="txtFileUpload3">Required.</asp:RequiredFieldValidator>
                        </div>
                    </div>
                </div>

                <div id="form-actions">
                    <asp:Button ID="btnPrevious" runat="server" Text="Previous" CssClass="btn btn-primary" />
                    <asp:Button ID="btnNext" runat="server" Text="Next" CssClass="btn btn-default" OnClick="btnNext_Click" />
                </div>

                <!-- PAGE CONTENT ENDS -->
            </div>
            <!-- /.col -->
        </div>
        <!-- /.row -->
    </div>
    <!-- /.page-content -->
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ScriptsContent" runat="server">
    <script src="<%=ResolveUrl("~/assets/js/jquery.maskedinput.min.js")%>"></script>
    <script src="../Scripts/WebForms/WebUIValidation.js"></script>
    <script type="text/javascript">


        $(document).ready(function () {
            $('#TTSRB').change(function () {
                if (this.checked) {
                    $('#TTS').removeClass("Invisible");
                    $('#RecordPhone').addClass("Invisible");
                    $('#UploadFile').addClass("Invisible");
                    var valRequiredFieldValidator1 = $("[id*=RequiredFieldValidator1]");
                    ValidatorEnable(valRequiredFieldValidator1[0], true);
                    var valRequiredFieldValidator2 = $("[id*=RequiredFieldValidator2]");
                    ValidatorEnable(valRequiredFieldValidator2[0], false);
                    var valRequiredFieldValidator3 = $("[id*=RequiredFieldValidator3]");
                    ValidatorEnable(valRequiredFieldValidator3[0], false);
                }
            });

            $('#RecordPhoneRB').change(function () {
                if (this.checked) {
                    $('#TTS').addClass("Invisible");
                    $('#RecordPhone').removeClass("Invisible");
                    $('#UploadFile').addClass("Invisible");
                    var valRequiredFieldValidator1 = $("[id*=RequiredFieldValidator1]");
                    ValidatorEnable(valRequiredFieldValidator1[0], false);
                    var valRequiredFieldValidator2 = $("[id*=RequiredFieldValidator2]");
                    ValidatorEnable(valRequiredFieldValidator2[0], true);
                    var valRequiredFieldValidator3 = $("[id*=RequiredFieldValidator3]");
                    ValidatorEnable(valRequiredFieldValidator3[0], false);
                }
            });

            $('#UploadFileRB').change(function () {
                if (this.checked) {
                    $('#TTS').addClass("Invisible");
                    $('#RecordPhone').addClass("Invisible");
                    $('#UploadFile').removeClass("Invisible");
                    var valRequiredFieldValidator1 = $("[id*=RequiredFieldValidator1]");
                    ValidatorEnable(valRequiredFieldValidator1[0], false);
                    var valRequiredFieldValidator2 = $("[id*=RequiredFieldValidator2]");
                    ValidatorEnable(valRequiredFieldValidator2[0], false);
                    var valRequiredFieldValidator3 = $("[id*=RequiredFieldValidator3]");
                    ValidatorEnable(valRequiredFieldValidator3[0], true);
                }
            });

            $('#<%=txtFileUpload3.ClientID%>').ace_file_input({
                no_file: 'No File ...',
                btn_choose: 'Choose',
                btn_change: 'Change',
                droppable: false,
                onchange: null,
                thumbnail: false
            });


            $.mask.definitions['~'] = '[+-]';
            $('.input-mask-date').mask('99/99/9999');
            $('.input-mask-phone').mask('(999) 999-9999');
            $('.input-mask-eyescript').mask('~9.99 ~9.99 999');
            $(".input-mask-product").mask("a*-999-a999", { placeholder: " ", completed: function () { alert("You typed the following: " + this.val()); } });


        });
    </script>


</asp:Content>

Open in new window

Validator.PNG
Avatar of Juan Carlos
Juan Carlos
Flag of Peru image

removes Required within the control, because it does not indicate the error message. It is usually used to put an * in front of the textbox to indicate that it is a required field.

<asp:RequiredFieldValidator 
CssClass="text-danger" ID="RequiredFieldValidator2" runat="server" 
Display="Dynamic" ErrorMessage="Required." ControlToValidate="TextBox1"></asp:RequiredFieldValidator> 

Open in new window

Here is working example

<form id="form1" runat="server">
    Your name:<br />
    <asp:TextBox runat="server" id="txtName" />
    <asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
    <br /><br />
    <asp:Button runat="server" id="btnSubmitForm" text="Ok" />
</form>
Avatar of FrankG77
FrankG77

ASKER

jcgd: I removed the extra "required" text that was there, but the result is the exact same. The ErrorMessage is still being triggered just by simply clicking the radio button.

Pravin Asar: I receive an error that says "Element 'form' must not be nested within element 'form.'" The first row of code has a green underline it. Even if I wasn't receiving this error, I want to avoid going server-side when the user clicks submit if the text box is empty. So I think I have to use Jquery to avoid that, right?
Try with : EnableClientScript=false

<asp:RequiredFieldValidator
EnableClientScript="false"
 CssClass="text-danger" ID="RequiredFieldValidator2" 
runat="server"
 Display="Dynamic" 
ErrorMessage="Required." 
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator> 

Open in new window

jcgd: That works, however when I click submit, it reaches the server side, despite the requirement not being fulfilled. I need it to prevent the submit button from reaching the server side.
Maybe this works:

- Switch to true  EnableClientScript="True"

- in javascript event include at first line: event.preventDefault().

    $('#TTSRB').change(function () {
                event.preventDefault();
                if (this.checked) {

Open in new window

If it does not work, then switch EnableClientScript="False" and the validation in the client will have to be done in the OnClientClick (return validate ()) event of the Asp:Button control. Where validate () is a javascript function that you must implement and return 'false' if the validation fails or 'true' to continue with the OnClick event of the server. However, this would no longer serve the ASP controls: RequireFieldValidator.

  <asp:TextBox ID="TextBox1" ClientIDMode="Static"  ...
...

<asp:Button ID="btnNext" runat="server" Text="Next" CssClass="btn btn-default" OnClick="btnNext_Click" OnClientClick="return validate()" />

---

// javascript code

     validate() {

           if ok return true;

          return false;
       }

Open in new window

I no longer need assistance with this issue, thank you.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.