我正在使用Parsley JS(http://parsleyjs.org/)进行表单验证。错误的默认行为是向每个无效输入添加一类parsley-error。但是,我想更改默认行为并将错误类添加到输入的父级中-特别是在form-group元素上。

基本的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>

我正在使用“Javascript安装”初始化所有内容,并尝试使用自己的函数覆盖“errorClass”和“successClass”选项,但似乎无法正常工作。
 $('.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>',
});

我想结束这样的事情:
<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>

最佳答案

您应该使用classHandler而不是errorClass

这应该工作:

$(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>',
    });
});

您也可以在SO上检查此相关答案:parsley 2.0.3 not working with boostrap 3

关于javascript - Parsley JS向父级添加错误/成功类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25594278/

10-11 14:05