Jquery验证不需要字段工具提示消息问题

时间:2016-09-09 13:29:47

标签: jquery twitter-bootstrap jquery-validate

我正在使用jquery验证并使用引导工具提示显示错误消息。这工作正常,但是当我在不需要的字段中插入不正确的值,然后删除文本并将该字段留空时,输入中的高亮效果消失但工具提示仍然可见。

JS

$('#myform').validate({ // initialize the plugin
  onkeyup: false,
  rules: {
    field1: {
      required: true,
      number: true
    },
    field2: {
      number: true
    }
  },
  errorPlacement: function (error, element) {
    var lastError = $(element).data('lastError'),
        newError = $(error).text();
    $(element).data('lastError', newError);
    if (newError !== '' && newError !== lastError) {
      $(element).tooltip({
        placement: "bottom",
        trigger: "manual"
      }).attr('title', newError).tooltip('fixTitle').tooltip('show');
    }
  },
  success: function (label, element) {
    $(element).tooltip('hide');
  }
});

HTML

<form id="myform">
  <input type="text" name="field1" />
  <input type="text" name="field2" />
  <input type="submit" />
</form>

要解决我的问题,我尝试使用取消强光方法,但只能在第一次使用,然后在同一字段中重新插入不正确的值时不再显示工具提示

 unhighlight: function(element, errorClass, validClass) {
    $(element).removeClass(errorClass).addClass(validClass);
    $(element).tooltip('hide');
 }

在第二个字段中键入文本,然后将其删除。 jsfiddle

如何解决我的问题?感谢

1 个答案:

答案 0 :(得分:1)

可以被认为是黑客工作,但是听blur事件并清空工具提示,如果是空的,可以很好地工作:

$("input").blur(function () {
  if (!this.value.trim().length)
    $(this).tooltip("hide");
});

<强>段

&#13;
&#13;
$('#myform').validate({ // initialize the plugin
  onkeyup: false,
  rules: {
    field1: {
      required: true,
      number: true
    },
    field2: {
      required: false,
      number: true
    }
  },
  errorPlacement: function(error, element) {
    var lastError = $(element).data('lastError'),
        newError = $(error).text();
    $(element).data('lastError', newError);
    if (newError !== '') {
      $(element).tooltip({
        placement: "bottom",
        trigger: "manual"
      }).attr('title', newError).tooltip('fixTitle').tooltip('show');
    }
  },
  success: function(label, element) {
    $(element).tooltip('hide');
  }
});
$("input").blur(function() {
  if (!this.value.trim().length)
    $(this).tooltip("hide");
});
&#13;
#myform {
  width: 600px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form id="myform">
  <input type="text" name="field1" />
  <input type="text" name="field2" />
  <input type="submit" />
</form>
&#13;
&#13;
&#13;

JsFiddle:https://jsfiddle.net/reo1ck3e/