Jquery Validate custom error message location

后端 未结 7 1743
一个人的身影
一个人的身影 2021-01-30 16:35

This looks very simply, but I can\'t figure it out. I\'m using the jquery validate plugin. I\'m trying to validate and

相关标签:
7条回答
  • 2021-01-30 17:23

    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>

    0 讨论(0)
提交回复
热议问题