3

I have a form, which I'm validating using JQuery Validation plugin. Validation works file until I add a Bootstrap 3 popover to the text field with name "taskName" (the one being validated) (please see below) . When I add the popover to this text field, error messages are repeatedly displayed every time the validation gets triggered. Please see the code excerpts and screenshots below.

I've been trying to figure out what is happening, with no success so far. Any help will be greatly appreciated. Thanks in advance!

HTLM Excerpt

The popover content

<div id="namePopoverContent" class="hide">
    <ul>
        <li><small>Valid characters: [a-zA-Z0-9\-_\s].</small></li>
        <li><small>Required at least 3 characters.</small></li>
    </ul>
</div>

The form

<form class="form-horizontal" role="form"  method="post" action="" id="aForm">
    <div class="form-group has-feedback">
        <label for="taskName" class="col-md-1 control-label">Name</label>
        <div class="col-md-7">
            <input type="text" class="form-control taskNameValidation" id="taskName" name="taskName" placeholder="..." required autocomplete="off" data-toggle="popover">
            <span class="form-control-feedback glyphicon" aria-hidden="true"></span>
        </div>
    </div>
    ...
</form>

JQuery Validate plugin setup

$(function() {
                //Overwriting a few defaults
                $.validator.setDefaults({
                    errorElement: 'span',
                    errorClass: 'text-danger',
                    ignore: ':hidden:not(.chosen-select)', 
                    errorPlacement: function (error, element) {
                       if (element.is('select'))
                           error.insertAfter(element.siblings(".chosen-container"));
                       else 
                           error.insertAfter(element);
                    }
                });

                //rules and messages objects
                $("#aForm").validate({
                    highlight: function(element) {
                        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
                        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                    },
                    success: function(element) {
                        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                    }
                });

                $('.taskNameValidation').each(function() {
                    $(this).rules('add', {
                        required: true,
                        alphanumeric: true,
                        messages: {
                            required: "Provide a space-separated name."
                        }
                    });
                });
            });

Bootstrap 3 popover setup

$('[data-toggle="popover"]').popover({ 
            trigger: "focus hover",
            container: "body",
            html: true,
            title: "Name Tips",
            content: function() { return $('#namePopoverContent').html();}
        });

The screenshots Screenshot 1 Screenshot 2

First Edit

It seems I did not make my question clear, so here it goes my first edit.

I'm not using the popover to display the error messages of the validation. The error messages are inserted after each of the fields that fail validation, which is precisely what I want. Hence, this question does not seem to be a duplicate of any other question previously asked.

Regarding the popover, I just want to add an informative popover that gets displayed whenever the user either clicks the text field "taskName" or hovers the mouse over it. Its role is completely independent of the validation.

The question is, then, why adding the (independent) popover is making the validation plugin misbehave, as shown in the screenshots.

dml
  • 133
  • 2
  • 12

2 Answers2

6

I had the very same issue a few days ago and the only solution I found was to use 'label' as my errorElement:.

Change the line errorElement: 'span' to errorElement: 'label' or simply removing the entire line will temporarily fix the issue. ('label' is the default. )

I am not completely sure what the JQ validate + BS popover conflict is, but I will continue to debug.

After some debugging I think I found the issue.

Both jQuery validate and bootstrap 3 popovers are using the aria-describedby attribute. However, the popover code is overwriting the value written by jQuery validate into that attribute.

Example: You have a form input with an id = "name", jQuery validate adds an aria-describedby = "name-error" attribute to the input and creates an error message element with id = "name-error" when that input is invalid.

using errorElement:'label' or omitting this line works because on line 825 of jquery.validate.js, label is hard-coded as a default error element selector.

There are two ways to fix this issue:

  1. Replace all aria-describedby attributes with another attribute name like data-describedby. There are 4 references in jquery.validate.js. Tested.

or

  1. Add the following code after line 825 in jquery.validate.js. Tested.

if ( this.settings.errorElement != 'label' ) { selector = selector + ", #" + name.replace( /\s+/g, ", #" ) + '-error'; }

I will also inform the jQuery validate developers.

Bob Marley
  • 238
  • 1
  • 9
  • Actually, this solved the issue. Using the default value of errorElement messes up now with the positioning of the bootstrap glyphicons (ok and remove), but the error messages are no longer being repeated over and over. Thank you! – dml May 30 '15 at 01:07
  • I've added some possible solutions. – Bob Marley Jun 02 '15 at 17:48
  • Here is a link to the related issue in the jQuery Validation repo that @BobMarley posted: https://github.com/jquery-validation/jquery-validation/issues/1494 – Ryan Griffith Jan 03 '23 at 22:05
0

The success option should only be used when you need to show the error label element on a "valid" element, not for toggling the classes.

You should use unhighlight to "undo" whatever was done by highlight.

highlight: function(element) {
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
},
unhighlight: function(element) {
     $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
     $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}

(The success option could also be used in conjunction with the errorPlacement option to show/hide tooltips or popovers, just not to do the styling, which is best left to highlight and unhighlight.)


Also, I recommend letting the Validate plugin create/show/hide the error label element, rather than putting it the markup yourself. Otherwise, the plugin will create its own and ignore the one you've created.


In case you were unaware, you cannot use the alphanumeric rule without including the additional-methods.js file.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Thanks for your reply! One question: When I add the definition of _unhighlight_, a textarea field that I have on the form gets applied the has-success class. Do you know why by any chance? – dml May 29 '15 at 20:19
  • BTW, the problem persists. Just want to make sure I emphasize the fact that the problem seems to be unrelated to the initial exclusion of unhighlight. And yes, I have linked to the additional_methods.js file. Thanks for the clarification, though. In fact, the validation works just fine before adding the informative popover, which is not related to the form validation. – dml May 29 '15 at 20:20
  • @user2669241, please setup a jsFiddle that reproduces your issue. – Sparky May 29 '15 at 20:30
  • @SparkyI'll ask a different question concerning the new issue I'm facing and I'll set up a jsFiddle for illustration. That way I can give the deserved credit to any person who takes the time to help. – dml May 30 '15 at 01:10
  • Posted a new question (http://stackoverflow.com/questions/30548059/bootstrap-3-validation-states-with-jquery-validated-form-that-uses-chosen-plugin), with jsFiddle. – dml May 30 '15 at 15:43