Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery validate plugin how to add error class to label

Using the jquery validate plugin and I'm trying to override it's default behavior. this is an example of my html:

<table>
<tr>
  <td>
    <label for="my-input>Name</label>
  </td>
</tr>
<tr>
  <td>
    <input type="text" class="required" id="my-input />
  </td>
</tr>
</table>

All I want the valadate to do is add the class .error to the existing label, and then remove it once the field passes validation.

Thanks.

like image 706
Strontium_99 Avatar asked Jan 31 '13 13:01

Strontium_99


People also ask

How do I show different errors in jQuery validator addMethod?

validator. addMethod('min-length', function (val, element) { // do stuff // the error message here needs to be dynamic }, 'The field cannot be less than than ' + element. attr('data-min') + // it is within the closure, but it can't grab it ' length. ');

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.


2 Answers

this is the default behaviour, you just need to stop the error message being displayed on the page. You can do this by overriding errorPlacement

$('form').validate({
 errorPlacement: function () { }
});

EDIT.

sorry misread the question bit - the code below works but there is probably a better way

$('form').validate({
    // make sure error message isn't displayed
    errorPlacement: function () { },
    // set the errorClass as a random string to prevent label disappearing when valid
    errorClass : "bob",
    // use highlight and unhighlight
    highlight: function (element, errorClass, validClass) {
        $(element.form).find("label[for=" + element.id + "]")
        .addClass("error");
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element.form).find("label[for=" + element.id + "]")
        .removeClass("error");
    }
});

the above code comes from the highlight example on the options docs

like image 186
Dr Blowhard Avatar answered Oct 24 '22 09:10

Dr Blowhard


errorElement: "label",
errorPlacement: function(error, element) {
    error.insertBefore(element.parent().children("br"));
},
highlight: function(element) {
    $(element).parent().addClass("error");
},
unhighlight: function(element) {
    $(element).parent().removeClass("error");
}
like image 40
SpareMe Avatar answered Oct 24 '22 08:10

SpareMe