locked
Is it possible to modify this JS to add validation group? RRS feed

  • Question

  • User1216627406 posted

    Greetings again mates,

    I have two button controls for adding two different records into the the DB.

    Let's say one is called btn1Add and the other is btn2Add

    When the textbox controls for each is empty and you click the Add button, regardless of whether you click btn1Add or btn2Add, controls for both are highlighted requiring that you enter values into them before submitting.

    I would like to use javascript for this validation instead of requiredFieldValidator control.

    The following JS works fine if I was using just one button control.

    Is there a way to add Validation Group to the JS so that it only validates the control group associated with a particular button?

        <script type="text/javascript">
            $(document).ready(function () {
                $('#btn1Add').click(function (e) {
                    var isValid = true;
                    $('input[type="text"]').each(function () {
                        if ($.trim($(this).val()) == '') {
                            isValid = false;
                            $(this).css({
                                "border": "1px solid red",
                                "background": "#FFCECE"
                            });
                        }
                        else {
                            $(this).css({
                                "border": "",
                                "background": ""
                            });
                        }
                    });
                    if (isValid == false)
                        e.preventDefault();
                    else
                        alert('Thank you for submitting');
                });
            });
     </script>
    <asp:ImageButton ID="btn1Add" runat="server" Height="20px" ImageUrl="~/Images/add.png" validationgroup="SpeakersInfoGroup" onclick="Insert" Width="20px" />

    Above is just one of the JS for the btn1Add validator.

    I hope my need is clear.

    Thank you very much in advcance

    Thursday, May 20, 2021 2:56 AM

All replies

  • User753101303 posted

    Hi,

    It's been a while but it could be interesting to have a look at the default implementation. If I remember it renders an array with the validation information and can then validate contorls matching the button validation group.

    If you want to create your own you could perhaps have a data-validationgroup attribute on controls anb buttons and trake that into account if found...

    Thursday, May 20, 2021 7:30 AM
  • User1535942433 posted

    Hi simflex,

    You could use jquery.validate Plugin.

    $("#signupForm").validate({
        groupname:.....;
        })

    https://www.runoob.com/jquery/jquery-plugin-validate.html

    Best regards,

    Yijing Sun

    Thursday, May 20, 2021 7:43 AM
  • User1216627406 posted

    Hi PatriceSC, not sure I follow.

    yij sun, from what I am able to understand from the link you posted, you can use groups only for error messaging.

    Everything else still gets validated which doesn't help me much.

    Did I read it wrong?

    Take my case for instance, two submit buttons, btn1Add and btn2Add, using your group recommendation, how should be implemented using the sample from your link below?

    $("#myform").validate({
        groups:{
            username:"fname 
            lname"
        },
        errorPlacement:function(error,element) {
            if (element.attr("name") == "fname" || element.attr("name") == "lname")   
                error.insertAfter("#lastname");
            else    
                error.insertAfter(element);
        },
       debug:true
    })

    Thursday, May 20, 2021 2:49 PM
  • User-474980206 posted

    you need to add the validationGroup to the inputs. then on validation, check if they match:

     $(document).ready(function () {
         $('#btn1Add').click(function (e) {
             var group = $(this).attr("validationGroup");
             var isValid = true;
             $('input[type="text"][validationGroup="' + group + '"]').each(function () {

    note: you could also update the jquery validation ignore selector before calling its valid()

     

    $.validator.setDefaults({ ignore: [":not([validationGroup=" + group + "])"]});
    Thursday, May 20, 2021 3:34 PM
  • User1216627406 posted

    Thank you Bruce for the script.

    Even the script looks very elegant, I could not get it to work and for fear of asking for further assistance with it, I found this sample code:

       <script type = "text/javascript">
        function VerifyAndSave(groupName) {
            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate(groupName);
            }
            if (Page_IsValid) {
                alert(groupName + "Validations successful");
                //do something
            }
        }
       </script>

    This script gives me close to what I was looking for because I ended up using it along with RequireFieldValidator control:

                            <td style="width: 170px">
                                <asp:TextBox ID="txtsermonnotes1" TextMode="MultiLine" Placeholder="Enter Sermon Notes..." runat="server" Width="150" />
    <asp:RequiredFieldValidator ID="valsermonnotes" ValidationGroup = "SermonsInfoGroup"
    ControlToValidate = "txtsermonnotes1" runat="server" ErrorMessage="Required" />
                            </td>
                            <td style="width: 170px">
                             <asp:ImageButton ID="sbtnAdd" runat="server" Height="20px"   
                                ImageUrl="~/Images/add.png" OnClientClick="VerifyAndSave('SermonsInfoGroup')" onclick="smInsert"   
                                Width="20px" />
                            </td>
    
                                <asp:TextBox ID="txtcWebsiteURL1" Placeholder="Enter Website URL..." runat="server" Width="150" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" ControlToValidate = "txtcWebsiteURL1"
    runat="server" validationgroup="SpeakersInfoGroup" ErrorMessage="*Required" />
    
                            </td>
                            <td style="width: 170px">
                             <asp:ImageButton ID="imgbtnbackground" runat="server" Height="20px"   
                                ImageUrl="~/Images/add.png" OnClientClick="VerifyAndSave('SpeakersInfoGroup')" onclick="Insert"   
                                Width="20px" />
                            </td>

    My only two misgivings about using it are (1), when used with popup calendar, it doesn;t hide the "Reguired" mesage and second, the only way to truly validate email address is to use two types, one that says "email required" and one that says "invalid email" I would have preferred one line of code for that but for now, I guess I just settle for "Email required" message/

    Thursday, May 20, 2021 11:10 PM
  • User1535942433 posted

    Hi simflex,

    Do you have press F12 to check what's error?

    Best regards,

    Yijing Sun

    Friday, May 21, 2021 8:24 AM
  • User1216627406 posted

    Yes, but no errors.

    Pretty much everything is working fine now except that I can't get RequiredValidator control to validate jquery datepicker but other than that, pretty much everything is working fine.

    Friday, May 21, 2021 5:00 PM
  • User1535942433 posted

    Hi simflex,

    How do you write jquery datepicker? The control does not have a "sever" id,which means it only exists on the client/browser side. You must assign "server" id by forcing the control to "run" at the server, so you must add runat="server".

    More details,you could refer to below article:

    https://stackoverflow.com/questions/22667080/regular-field-validator-and-jquery-datepicker-in-asp-net

    Best regards,

    Yijing Sun

    Tuesday, May 25, 2021 9:15 AM
  • User1216627406 posted

    Sorry sir but my codes all have runat="server" attributes.

    Maybe, I am missing something with your post.

    Wednesday, May 26, 2021 6:13 PM
  • User1535942433 posted

    Hi simflex,

    I suggest you post codes about RequiredValidator with jquery datepicker. Since you don't post in your thread,I don't know what' the errors.

    Best regards,

    Yiijing Sun

    Thursday, May 27, 2021 2:20 AM