How to display messages from jQuery Validate plugin inside of Tooltipster tooltips?
Asked Answered
E

2

20

I'd like to use the Tooltipster plugin to display form errors generated by the jQuery Validate plugin.

jQuery for Validate plugin:

$(document).ready(function () {

    $('#myform').validate({ // initialize jQuery Validate
        // other options,
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

jQuery for Tooltipster plugin:

$(document).ready(function () {

    $('.tooltip').tooltipster({ /* options */ });  // initialize tooltipster

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <br/>
    <input type="submit" />
</form>

How would I integrate the usage of these two jQuery plugins so that validation errors appear inside the tooltips?

Equivalent answered 7/2, 2013 at 0:46 Comment(0)
E
42

Solutions for Tooltipster versions 2.1, 3.0, & 4.0 are included in this answer.

NOTE that .tooltipster() is only attached to a type="text" input element in my examples below. If your form contains other kinds of data input elements such as type="radio", type="date", textarea, select, etc., then you must adjust your selector accordingly or create additional instances of .tooltipster() for these other elements. Otherwise, everything will fail with errors.


Tooltipster v2.1

First, initialize the Tooltipster plugin (with any options) on all specific form elements that will display errors:

$(document).ready(function () {

    // initialize tooltipster on form input elements
    $('#myform input[type="text"]').tooltipster({ 
        trigger: 'custom', // default is 'hover' which is no good here
        onlyOne: false,    // allow multiple tips to be open at a time
        position: 'right'  // display the tips to the right of the element
    });

});

Second, use Tooltipster's advanced options along with the success: and errorPlacement: callback functions built into the Validate plugin to automatically show and hide the tooltips as follows:

$(document).ready(function () {

    // initialize validate plugin on the form
    $('#myform').validate({
        // any other options & rules,
        errorPlacement: function (error, element) {
            $(element).tooltipster('update', $(error).text());
            $(element).tooltipster('show');
        },
        success: function (label, element) {
            $(element).tooltipster('hide');
        }
    });

});

Working Demo: http://jsfiddle.net/2DUX2

EDIT: Updated code to take advantage of the new Tooltipster API features released in version 2.1 on 2/12/13



UPDATE for Tooltipster v3.0

Tooltipster 3.0 is out and as such doesn't work the same as illustrated above. The following code provides an updated example. This version has the added benefit of not calling Tooltipster on every keystroke when the message has not yet changed.

(Don't forget that you still need to attach .tooltipster() to your relevant input elements as illustrated above.)

$(document).ready(function () {

    // initialize validate plugin on the form
    $('#myform').validate({
        // any other options & rules,
        errorPlacement: function (error, element) {
            var lastError = $(element).data('lastError'),
                newError = $(error).text();

            $(element).data('lastError', newError);

            if(newError !== '' && newError !== lastError){
                $(element).tooltipster('content', newError);
                $(element).tooltipster('show');
            }
        },
        success: function (label, element) {
            $(element).tooltipster('hide');
        }
    });

});

DEMO using Tooltipster v3.0: jsfiddle.net/2DUX2/3/



UPDATE for Tooltipster v4.0

Note that the onlyOne option has been removed from the 4.0 version of the Tooltipster plugin.

I also replaced the success callback with unhighlight. On "optional" fields, the error message was never removed when the field was subsequently blanked out... this is because the success function does not fire under these circumstances. This issue is not isolated to Tooltipster version 4, however the following code solves it moving forward.

// initialize Tooltipster on text input elements
$('input[type="text"]').tooltipster({ //find more options on the tooltipster page
    trigger: 'custom', // default is 'hover' which is no good here
    position: 'top',
    animation: 'grow'
});

// initialize jQuery Validate
$("#myform").validate({
    errorPlacement: function (error, element) {
        var ele = $(element),
            err = $(error),
            msg = err.text();
        if (msg != null && msg !== '') {
            ele.tooltipster('content', msg);
            ele.tooltipster('open');
        }
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
    },
    rules: {
        ....

DEMO using Tooltipster v4.0: https://jsfiddle.net/h5grrrr9/

Equivalent answered 7/2, 2013 at 0:46 Comment(10)
I am trying to use your JS but I get this error and not sure how to solve it as i am new to JS: TypeError: $(...).validate is not a function  submitHandler: function (form) { // for demoControversy
@starbucks, sounds like you forgot to include the code for the jQuery Validate plugin.Equivalent
Yes, I fixed it. How can i highlight a missed field using your code? i am new to js and not sure at alll how to tackle it. Thanks!Controversy
@starbucks, Click this link and browse my other answers for something similar. Otherwise, feel free to read the FAQ and post a new question, because the comments section is not the place for new issues/questions.Equivalent
@Equivalent Great question and even better answer!! :) Unfortunately, I can't get it to work with dynamically created controls :(Schaffner
@eddy, there's no reason why it shouldn't. Maybe post a new question and include your code.Equivalent
@Equivalent I have created a jsFiddle jsfiddle.net/edaloicaro18/FKY9m/10 I tried using $('selector').tooltipster(); with type selector and class selector(see class tooltip), but neither approach worked :(Schaffner
@eddy, I'm sorry you're having problems but hijacking comments on another question's answer is not the proper way to ask for help here. Please post a whole new question as I stated already.Equivalent
@Equivalent Is there a way to make it so the tooltip only shows when hovering over the field with the error in it? Perhaps only initialize the tooltip if there is an error message?Cleavable
@user1404617, since the default is hover, don't over-ride with custom. Then look at how/where open and close are implemented above, and don't do those either. Just try it.Equivalent
G
2

Sparky's answer has been a staple on my site's validation, but upgrading to Tooltipster 4 required some changes. Here's how I got mine working, and with a few improvements.

On your pages, include the tooltipster css and a theme css in the head section (and any theme css that you subclass their themes with as described on its page).

<link rel="stylesheet" type="text/css" href="/styles/tooltipster.bundle.css">
<link rel="stylesheet" type="text/css" href="/styles/tooltipster/sideTip/themes/tooltipster-sideTip-light.min.css">

Additionally, you need to include tooltipster's javascript file. You'll also need the jquery-validation javascript.

<script src="/js/tooltipster.bundle.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>

Now, in either another javascript file or in some script tags, you'll need to put your validation code as well as your tooltipster code. Here's one from a webpage I have, the changes from Sparky's answer are at the top.

$(document).ready(function(){

    $('#form input[type="text"]').tooltipster({ //find more options on the tooltipster page
        trigger: 'custom', // default is 'hover' which is no good here
        onlyOne: false,    // allow multiple tips to be open at a time
        position: 'top',
        animation: 'grow', 
        theme: ['tooltipster-light'] //put your themes here
    });

    //form validation initialization
    $("#form").validate({
        errorPlacement: function (error, element) {
            if (error[0].innerHTML != null && error[0].innerHTML !== "") {
                $(element).tooltipster('content', $(error).text());
                $(element).tooltipster('open'); //open only if the error message is not blank. By default jquery-validate will return a label with no actual text in it so we have to check the innerHTML.
            }
        },
        success: function (label, element) {
            var obj = $(element);
            if (obj.hasClass('tooltipstered') && obj.hasClass('error')) {
                $(element).tooltipster('close'); //hide no longer works in v4, must use close
            }   
        },
        rules: {
            // your rules
            ......
        }
    });

});

Now when you type something into a field that violates one of the listed rules, a popup comes up above the box saying what jquery-validate says is wrong. It also won't open a message if there is nothing in it to show the user (which would lead to it opening a blank tooltip and then immediately closing, which looks weird).

Genitals answered 29/9, 2016 at 15:16 Comment(8)
Why use error[0].innerHTML when you can just look at $(error).text()?Equivalent
In your success, if var obj = $(element), then why not use obj.tooltipster('close') ?Equivalent
Also note that the onlyOne option has been removed from Tooltipster.Equivalent
I edited my answer to incorporate your solution into mine including a jsFiddle. Thank you for posting your answer.Equivalent
This answer fails when the field is "optional". Error message persists. Working on a solution now.Equivalent
Finally, there is no point to conditionally check for tooltipsered or error classes when you're not conditionally checking for similar things within the errorPlacement function.Equivalent
This solution addresses a tooltipster error in the Sparky example when input type != text (e.g. date).Mushro
@JimSTAT, of course it's expected that you would use the proper jQuery selectors for your particular project. Mine is specifically targeting only type="text" elements so adjust yours accordingly.Equivalent

© 2022 - 2024 — McMap. All rights reserved.