最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery validation for select box onchange - Stack Overflow

programmeradmin3浏览0评论

i design show/hide div select box using select2 and validate using jquery validation plugin. this worked but when i select empty value(select a color) validation show success (green color) but if i click submit button i see red color.

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>

Now, i need to show red color after choose empty value(on change). how do can fix this ?

JSFIDDLE

i design show/hide div select box using select2 and validate using jquery validation plugin. this worked but when i select empty value(select a color) validation show success (green color) but if i click submit button i see red color.

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>

Now, i need to show red color after choose empty value(on change). how do can fix this ?

JSFIDDLE

Share Improve this question edited Jul 29, 2014 at 7:47 user27133 asked Jul 29, 2014 at 7:31 user27133user27133 4874 gold badges16 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4 +50

Add new validation method right after the ready function

$.validator.addMethod("valueNotEquals", function(t, n, r) {
  return t != r
}, $.validator.format("Invalid val is supplied."));

Validation rules should look like

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

And of course do not forget to add name attribute to your select like in the rules declared above + placeholder option's value should be the value provided in rules (in this case 0)

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

UPDATE I noticed that if the value of placeholder option is changed the placeholder disappears, so I searched for another solution and found one:

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

Checkout the fiddle

发布评论

评论列表(0)

  1. 暂无评论