Jquery Validate custom error message location

You can simply create extra conditions which match the fields you require in the same function. For example, using your code above...

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            //Custom position: first name
            if (element.attr("name") == "first" ) {
                $("#errNm1").text(error);
            }
            //Custom position: second name
            else if (element.attr("name") == "second" ) {
                $("#errNm2").text(error);
            }
            // Default position: if no match is met (other fields)
            else {
                 error.append($('.errorTxt span'));
            }
        },
        rules
});

Hope that helps!


What you should use is the errorLabelContainer

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorElement : 'div',
    errorLabelContainer: '.errorTxt'
  });
});
.errorTxt{
  border: 1px solid red;
  min-height: 20px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" />
  <input type="text" name="second" />
  <div class="errorTxt"></div>
  <input type="submit" class="button" value="Submit" />
</form>

If you want to retain your structure then

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorPlacement: function(error, element) {
      var placement = $(element).data('error');
      if (placement) {
        $(placement).append(error)
      } else {
        error.insertAfter(element);
      }
    }
  });
});
#errNm1 {
  border: 1px solid red;
}
#errNm2 {
  border: 1px solid green;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" data-error="#errNm1" />
  <input type="text" name="second" data-error="#errNm2" />
  <div class="errorTxt">
    <span id="errNm2"></span>
    <span id="errNm1"></span>
  </div>
  <input type="submit" class="button" value="Submit" />
</form>