简体   繁体   中英

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.

$("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.

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. 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(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. See the trigger documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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