Ivasoft Ivasoft - 1 year ago 57
jQuery Question

How to validate two fields in one error in Jquery Validation

I have a two fields of date_start and date_end and I want to validate both in jqury Validation

I have a two error from validator but I need just one
enter image description here

part of java JSP form

<div class="form-group user-edit-form-group">
<label for="input_cameras_limit" class="col-xs-4 control-label">Cameras limit</label>

<div class="col-xs-4">
<input name="key_cameras_limit" id="input_cameras_limit" type="text"
class="form-control user-edit-input" placeholder="" value="">
</div>

<div class="user-edit-error-wrapper">
</div>
</div>


JS validation part

$('#partner_key_settings_form').validate({

rules: {
key_valid_from: {
required: true,
date: true
},
key_valid_till: {
required: true,
date: true
}

},
messages: {
key_valid_from: {
required: JsMultiLang.getWords('partner', 'validationPromoCodeDate')

},
key_valid_till: {
required: JsMultiLang.getWords('partner', 'validationPromoCodeDate')
}
},

errorClass: "user-search-error",

errorPlacement: function (error, element) {

if (element.attr("name")=="key_valid_from" ||element.attr("name")=="key_valid_till"){
error.appendTo($(element).parent().parent().parent().find('.user-edit-error-wrapper'));
console.log(error.appendTo($(element).parent().parent().parent().find('.user-edit-error-wrapper')==undefined))
}

},

highlight: function (element) {
$(".user-edit-server-error").remove();
$(element).closest('.form-group').addClass('has-error');

var tabPaneId = $(element).closest('.tab-pane').attr('id');
$('a[href="#' + tabPaneId + '"]').addClass('has-error');
},

unhighlight: function (element, error, valid) {
$(element).closest('.form-group').removeClass('has-error');

var tabPaneId = $(element).closest('.tab-pane').attr('id');
var hasErrorDivsId = '#' + tabPaneId + ' .has-error';
var errorDivsOnTabSize = $(hasErrorDivsId).size();
if (errorDivsOnTabSize < 1) {
$('a[href="#' + tabPaneId + '"]').removeClass('has-error');
}
},

success: function (error) {
error.remove();

}
})

Answer Source

You need to add a group object for grouping the validation and errorPlacement if you needed.

rules: {
    key_valid_from: {
      required: true,
      date: true
    },
    key_valid_till: {
      required: true,
      date: true
    }

  },
  groups: {
    key_valid_from: "key_valid_from key_valid_till"
  },
  errorPlacement: function(error, element) {
    if (element.attr("name") == "key_valid_from" || element.attr("name") == "key_valid_till")
      error.insertAfter('input[name=key_valid_till]');
    else
      error.insertAfter(element);
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download