选择框onchange的jquery验证

时间:2014-07-29 07:31:01

标签: javascript jquery jquery-validate

我使用select2设计show / hide div选择框并使用jquery验证插件进行验证。这工作,但当我选择空值(选择一种颜色)验证显示成功(绿色)但如果我点击提交按钮,我看到红色。

JS:

 $(document).ready(function () {
     $(".lstColors").change(function () {
         $('div.box').hide();
         $('div.box.' + $(this).val()).show();
     }).change();


     $('form').validate({
         rules: {
             firstname: {
                 minlength: 3,
                 maxlength: 15,
                 required: true
             },
             lastname: {
                 minlength: 3,
                 maxlength: 15,
                 required: true
             }
         },
         highlight: function (element, errorClass, validClass) {
             if (element.type === "radio") {
                 this.findByName(element.name).addClass(errorClass).removeClass(validClass);
             } else {
                 $(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
                 $(element).closest('.form-group').find('i.fa').remove();
                 $(element).closest('.form-group').append('<i class="fa icon-plane icon-2x form-control-feedback"></i>')
             }
         },
         unhighlight: function (element, errorClass, validClass) {
             if (element.type === "radio") {
                 this.findByName(element.name).removeClass(errorClass).addClass(validClass);
             } else {
                 $(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
                 $(element).closest('.form-group').find('i.fa').remove();
                 $(element).closest('.form-group').append('<i class="fa icon-plane icon-2x  form-control-feedback"></i>');
             }
         },
         errorElement: 'span',
         errorClass: 'help-block',
         errorPlacement: function (error, element) {
             if (element.parent('.input-group').length) {
                 error.insertAfter(element.parent());
             } else {
                 error.insertAfter(element);
             }
         }
     });

     $('form').on('submit', function () {
         $(this).addClass('submitted');
     });

     $("#lstColors").select2({
         placeholder: "Select a Color",
         triggerChange: true,
         allowClear: true,
         width: "200px"
     }).on('change', function () {
         if ($('form').hasClass('submitted')) $('form').valid();
     });
 });

HTML:

<form>
    <div class="form-group">
        <label class="control-label" for="firstname">Nome:</label>
        <div class="col-md-6">
            <div class="row">
                <div class="col-md-3">
                    <div class="input-group select2-bootstrap-prepend"> <span class="input-group-addon"><i class=" icon-male"></i></span>

                        <input class="form-control" placeholder="Insira o seu nome próprio" name="firstname" type="text" />
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="lstColors" class="control-label">Favorite Colors:</label>
        <div class="col-md-6">
            <div class="row">
                <div class="col-md-3">
                    <div class="input-group select2-bootstrap-prepend">
                        <select id="lstColors" class="lstColors required">
                            <option value=""></option>
                            <option value="red" selected>Red</option>
                            <option value="green">Green</option>
                            <option value="blue">Blue</option>
                        </select>
                        <div class="red box">test</div>
                        <div class="green box">You have selected <strong>green option</strong> so i am here</div>
                        <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

现在,我需要在选择空值(更改后)后显示红色。怎么能解决这个问题?

JSFIDDLE

1 个答案:

答案 0 :(得分:4)

在就绪功能

之后立即添加新的验证方法
$.validator.addMethod("valueNotEquals", function(t, n, r) {
  return t != r
}, $.validator.format("Invalid val is supplied."));

验证规则应该是

rules: {
  firstname: {
    minlength: 3,
    maxlength: 15,
    required: true
  },
  lastname: {
    minlength: 3,
    maxlength: 15,
    required: true
  },
  mySelect: {
    valueNotEquals: 0
  }
},

当然不要忘记将name属性添加到您的选择中,就像在上面声明的规则中一样,+占位符选项的值应该是规则中提供的值(在这种情况下为0)

<select id="lstColors" name="mySelect" class="lstColors required">
  <option value="0"></option>

<强>更新 我注意到如果占位符选项的值被更改,占位符就会消失,所以我搜索了另一个解决方案并找到了一个:

$(".lstColors").on('select2-removed', function () {
  if ($('form').hasClass('submitted')) $('form').valid();
});

结帐fiddle