tjans
tjans

Reputation: 1554

jquery validate - container doesn't hide when nonrequired regex validation has occurred

I have jquery validation working so that when validation occurs, the errors get placed into a container instead of inline.

I'm having an issue with some of my non-required fields. See the jsfiddle below for the code. Here's a brief overview:

Name: required field
Comment: required field
Url: not required, but class='url' to insure valid url
Email: not required, but class='email' to insure valid email

To reproduce:
Enter the value foo into the email field OR the url field and tab off
You'll get the "email is invalid" error as expected.
Go back into the field and clear it out and tab off
The error will go away, but the error container is still there (you can see the red outline at the top)

It seems that for regex type validation, if the field isn't required, it's not resetting back to ignoring validation when there's no value in there. If I go in and actually fix the error, e.g., making the email [email protected], everything works fine.

How can I get the validation to accept a blank value as valid for non-required fields?

jsfiddle link: http://jsfiddle.net/tjans/napf7/

Upvotes: 3

Views: 587

Answers (3)

Mahesh KP
Mahesh KP

Reputation: 6446

Use unhighlight section in validation plugin.

Check this jsFiddle http://jsfiddle.net/napf7/44/

Upvotes: 0

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You can overwrite the showErrors method to provide your own functionality. Call the defaultShowErrors for the standard behavior. I wrote a quick version that checks for any errors in the error object hash and conditionally shows or hides the container. Try it out. You may also want to check hasOwnProperty on the object enumeration if you go with this solution.

$("#commentForm").validate({
    wrapper: 'div',
    showErrors: function(errors){
        var hasErrors = false;
        for (var e in errors){
           hasErrors = true;
           break;
        }

        if(hasErrors) $(this.settings.errorLabelContainer).show();
        else $(this.settings.errorLabelContainer).hide();

        this.defaultShowErrors();
    },
    errorLabelContainer: '#jserror'
});

Upvotes: 1

kei
kei

Reputation: 20491

Use errorClass

jQuery:

$(document).ready(function(){
    $("#commentForm").validate({
        wrapper: 'div',
        errorLabelContainer: '#jserror',
        errorClass: 'errorClass'
    });
  });​

Then move the border css rule to that error class. Style as necessary

#jserror {
    display:none;
}
.errorClass
{
  border:1px solid red;
}

DEMO

Upvotes: 2

Related Questions