Question

I'm using the jQuery validator plugin on this signup form.

The problem I'm having is that if I focus out of the input box and it contains an error (invalid email or empty box) and I then go on to fill out the form properly, whatever the last error was doesn't disappear.

So, for example, if I miss out the '@' when filling in my email address and get the "Please enter a valid email address." error, this error persists even after I put the '@' in.

Here's the code I'm using to initialise:

$(document).ready(function()
{
    $('#form').validate(
    {
        rules:
        {
            email:
            {
                required: true,
                email: true
            }
        },
        errorPlacement: function(error, element)
        {
            $('#hidden').html(error);
        }
    });
});

And here's my form:

<form id="form" role="form" class="form-inline" method="POST">
    <p id="p">Get notified when Shopaholic launches</p>
    <input type="email" name="email" class="form-control input-lg" id="inputEmail" placeholder="Enter email">
    <button type="submit" class="btn btn-primary btn-lg" data-dismiss="modal">Notify me</button>
</form>
<div type="hidden" id="hidden" class="p"></div>

UPDATE

Following Sparky's answer, the code that worked was this:

$(document).ready(function()
{
    $('#form').validate(
    {
        rules:
        {
            email:
            {
                required: true,
                email: true
            }
        },
        errorLabelContainer: "#hidden",
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
});
Was it helpful?

Solution

This is breaking the plugin...

errorPlacement: function(error, element) {
    $('#hidden').html(error);
}

error is an object, not HTML, and element is the input object that triggered the error.

The default function is: error.insertAfter(element)

Whatever the custom function, you really should use error and element objects as the plugin automatically toggles the visibility of its error object.

There are other options you can use if you don't want the messages inside of a label or if you want all messages to be placed inside another container.

See all options here: http://jqueryvalidation.org/validate/

OTHER TIPS

Use this instead:

$(document).ready(function()
 {
    $('#form').validate(
    {
      rules:
      {
        email:
        {
            required: true,
            email: true
        }
    },
    messages: {
        email: "Please enter a valid email address."
    }
    });
});

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top