简体   繁体   English

如果浏览器自动填写了字段,则触发jquery表单验证

[英]Trigger jquery form validation if field is autofilled by browser

I am using keyup to match a regular expression agains a users input to if the input matches what I want. 我正在使用 keyup来匹配正则表达式,又是用户输入,以输入是否与我想要的匹配。

$("input[name=vat]").keyup(function(){
    var vatVal = $(this).val();
    var vatReg = /^[0-9-]{6,}$/;
    if (!vatReg.test(vatVal)) {
        $(this).removeClass("success");
        $(this).addClass("error");
    } else {
        $(this).removeClass("error");
        $(this).addClass("success");
        if (!$("span[name=vaterror]").hasClass("hide")) {
            $("span[name=vaterror]").addClass("hide");
        }
    }
});

But I am having an issue with some browsers pre-filling form fields. 但是某些浏览器预填写表单字段时出现问题。 Like Chrome can pre-fill certain input fields for you if the user has set their browser settings to do so. 如果用户已设置浏览器设置,例如Chrome,Chrome可以为您预填充某些输入字段。

How can I trigger validation when this happens? 发生这种情况时如何触发验证?

My bad for thinking this is a duplicate, I interpreted it as selecting a browser suggested option, not the actual initial prefill on page load. 我认为这是重复项很不好,我将其解释为选择浏览器建议的选项,而不是页面加载时实际的初始预填充。

I'm pretty sure that there is still no way of catching the browser prefill as it happens before the document.ready() is triggered. 我很确定在触发document.ready()之前,仍然没有办法捕获浏览器的预填充。 But you can use that to your advantage. 但是您可以利用它来发挥自己的优势。

Simply trigger the event you are catching on the document.ready event, for all input fields which don't have the default value: 对于所有不具有默认值的输入字段,只需触发您在document.ready事件中捕获的事件:

$(document).ready(function(){
  $('input[value!=""]').trigger('keyup');
});

This code isn't tested, you may have to add the keyboard codes of a random key to the event if you use them in any handlers which listen to the keyup. 此代码未经测试,如果您在侦听keyup的任何处理程序中使用随机键的键盘代码,则可能必须将其添加到事件中。 See the trigger documentation . 请参阅触发器文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM