Robby Ceyssens
Robby Ceyssens

Reputation: 23

jquery validate custom error element with data message attribute

I'm using jquery validate and I want the error element in this format:

<div class="error-holder" data-error-message="Please correct this field"></div>

I already tried using the errorPlacement and errorElement option:

errorPlacement: function (error, element) {
        error = error.attr("class", "error-holder").attr("data-error-message", error.text()).text("");
        error.insertAfter(element);
    },
    errorElement: "div"

This produces the correct error element but when trying to submit the form (with other errors) the error element is duplicated each time.

How can I get the correct error element without the duplicates ?

Upvotes: 1

Views: 5241

Answers (2)

Robby Ceyssens
Robby Ceyssens

Reputation: 23

I solved this problem by first checking if the error div already exists:

errorPlacement: function (error, element) {
        error = error.attr("class", "error-holder").attr("data-error-message", error.text()).text("");
        if ($("div[for=" + element.attr("id") + "]").length == 0) {
            error.insertAfter(element);
        }
    }

I need this specific error div because of design requirements in css.

Thx for the replies !

Upvotes: 1

Sparky
Sparky

Reputation: 98738

The duplication is presumably being caused by putting this error container within your HTML markup ahead of time and then trying to target it...

error = error.attr("class", "error-holder").attr("data-error-message", ....

The plugin is automatically creating an error element in addition to yours and does not know (cannot find) which one to toggle.


You can set the error container to a div...

errorElement: "div"

And you can set the error class to error-holder...

errorClass: "error-holder"

However, there is no option on this plugin for setting a custom attribute for the error message container. It's unclear why you would need to put the error message inside of an attribute when the plugin dynamically creates and toggles the error messages automatically.

If you need custom error messages, there are various standard methods to achieve this that do not require creating static message elements in advance.

DEMO: http://jsfiddle.net/okwwrsd9/

$(document).ready(function () {

    $('#myform').validate({
        errorElement: "div",
        errorClass: "error-holder",
        rules: {
            foo: {
                required: true
            }
        },
        messages: {
            foo: {
                required: "Please correct this field"
            }
        }
    });

});

Upvotes: 0

Related Questions