Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsley JS Add Error/Success Class to Parent

I'm using Parsley JS (http://parsleyjs.org/) for form validation. The default behavior for errors is to add a class of parsley-error to each invalid input. However, I'd like to change up the default behavior and add the error class to the parent of the input - specifically on the form-group element.

The basic HTML

<form class="js-contact-form">

  <!-- this field is just required, it would be validated on form submit -->
  <div class="form-group">
    <label for="fullname">Full Name * :</label>
    <input type="text" class="form-control" name="fullname" placeholder="Name" required />
  </div>

  <!-- this required field must be an email, and validation will be run on field change -->
  <div class="form-group">
    <label for="email">Email * :</label>
    <input type="email" class="form-control" name="email" data-parsley-trigger="change" />
  </div>

  <input type="submit" />
</form>

I'm using the "Javascript Installation" to initialize everything and I tried overriding the "errorClass" and "successClass" options with my own function, but doesn't seem to work.

 $('.js-contact-form').parsley({
    trigger:      'change',
    errorClass:   function(){
      $(this).parent()
           .removeClass('has-success')
           .addClass('has-error has-feedback');
    },
    successClass: function(){
      $(this).parent()
           .removeClass('has-error')
           .addClass('has-success has-feedback');
    },
    errorsWrapper: '<div class="invalid-message"></div>',
    errorTemplate: '<span></span>',
});

I want to end up with something like this:

<div class="form-group has-feedback has-error">
  <label for="fullname">Full Name * :</label>
  <input type="text" class="form-control" name="fullname" placeholder="Name" required />
  <div class="invalid-message">
     <span>This field is required</span>
  </div>
</div>
like image 684
cusejuice Avatar asked Aug 31 '14 17:08

cusejuice


1 Answers

You should use classHandler instead of errorClass.

This should work:

$(document).ready(function() {
    $('.js-contact-form').parsley({
        trigger:      'change',
        successClass: "has-success",
        errorClass: "has-error",
        classHandler: function (el) {
            return el.$element.closest('.form-group'); //working
        },
        errorsWrapper: '<div class="invalid-message"></div>',
        errorTemplate: '<span></span>',
    });
});

You can also check this related answer here on SO: parsley 2.0.3 not working with boostrap 3

like image 51
Luís Cruz Avatar answered Oct 08 '22 09:10

Luís Cruz