jQuery 验证不适用于 Google 自动完成输入

jQuery validation is not working for Google autocomplete enter

我在表单中使用 google 自动完成和 jQuery 验证,它在以下情况下工作正常。

  1. 用户键入位置,使用自动完成他select通过鼠标单击输入值。
  2. 用户键入位置并移至下一个字段或单击任意位置,然后位置字段变为空。 (因为要求用户应该 select 值,他们不能输入和提交随机值)

以上条件正常。但是

  1. 用户键入位置,select通过单击输入按钮输入值。在这种情况下,值即将到来,但 jQuery 验证仍显示 please enter the location(请检查下图)。当用户单击某处或将光标移动到下一个字段时,只有错误消息会隐藏。

如果用户通过单击输入 select 值,则不应显示错误消息,因为值是 selected。如果这些值不是 selected,那么显示错误消息是可以的。

请帮助我。 DEMO

$( "form" ).validate({
    focusInvalid: false,
    submitHandler: function() {
        alert( "Successful submission" );         
    }
});

$("#locationTextField").on("blur", function () { 0 == $(this).val().trim().length ? ($("#locationTextField").parents("div").removeClass("has-error").addClass("success"), $("#locationTextField-error").hide()) : $("#locationTextField").removeClass("success").addClass("has-error")
    });
form > div {
    margin: 1em;
}
form button {
    width: 100%;
}
label { display: block; }
input {
    width: 100%;
    padding: 0.2em;
}
button {
    padding: 0.2em;
}
 
label.error {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&dummy=.js"></script>
<form>
    <div>
        <label for="name">Location:</label>
        <input type="text" id="locationTextField" style="color:#555 !important;" onChange="return validateCity()" placeholder="" name="location" class="form-control" required maxlength="150" data-msg-required="Please enter your location">
    </div>
    <div>
        <label for="name">Name:</label>
        <input type="text" placeholder="" name="name" class="form-control" required maxlength="150" data-msg-required="Please enter your name">
    </div>
    <div>
        <button>Submit</button>
    </div>
</form>

<script>
function initialize() {
    var e = document.getElementById("locationTextField");
    new google.maps.places.Autocomplete(e);
}

google.maps.event.addDomListener(window, "load", initialize);

function validateCity() {
    return searchfield = $("#locationTextField").val(), "" == searchfield || null == searchfield ? !1 : ($("#locationTextField").val(""), !1)
}
</script>

整个问题是由于 jQuery Validate 插件仅由 onkeyupfocusout 等用户交互触发的。由于您正在以编程方式更改此字段的值,始终跳过验证。

解决方案是使用插件的 .valid() 方法以编程方式简单地触发验证。但是,由于该字段由 Google 自动完成功能填充,您需要找到一个 built-in 事件,您可以利用它来调用 .valid()。 Google 提供了适用于此的 place_changed 事件。

  • 创建一个 Google 侦听器来检查 place_changed 事件。

  • 每当位置更改时,使用事件调用 .valid()。该字段将被验证,错误将照常自动 show/hide。

  • 删除内联 onChange 函数。不需要。

  • 删除整个 validateCity 函数。也不需要。

  • 删除您的 blur 处理函数。不需要,因为该插件旨在自动处理这些更改。

新代码:

function initialize() {
    var e = document.getElementById("locationTextField");
    var autocomplete = new google.maps.places.Autocomplete(e);
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        $('#locationTextField').valid();  // trigger validation after place selected
    });
}

google.maps.event.addDomListener(window, "load", initialize);  // initialize Google Maps

$("form").validate({  // initialize Validate plugin
    // options
});

演示:jsfiddle.net/x0jt2jux/1/

非常感谢@Sparky。

我一直在使用变量,但我想我会改用你的方法,这显然是真正的方法。无论如何,如果有人需要我的(即使我建议使用 Sparky 的答案),它是这样工作的:

(在页面加载时,设置 googleAdressFill = <b>0</b>,然后在执行 fillInAddress() 时,设置 googleAdressFill = <b>1</b>)

然后,为jQuery验证器添加一个使用addMethod函数的方法:

jQuery.validator.addMethod("myMethod", function(value, element) {
   if (googleAdressFill === 0) 
       return this.optional(element);
   else
       return true;
   }, "You need to enter and select address from suggestion.");

并在 jQuery 验证选项中声明新规则方法。

  rules: { nameOfInput: { myMethod: true } }