madsobel
madsobel

Reputation: 3257

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?

Upvotes: 0

Views: 2477

Answers (1)

caffeinated.tech
caffeinated.tech

Reputation: 6548

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.

Upvotes: 3

Related Questions