igorescobar / jQuery-Mask-Plugin

A jQuery Plugin to make masks on form fields and HTML elements.
http://igorescobar.github.io/jQuery-Mask-Plugin/
Other
4.77k stars 1.42k forks source link

firefox autofill phone number format #712

Open z1haze opened 5 years ago

z1haze commented 5 years ago

Device

Windows 10

Browser (and version)?

Firefox 65.0.2 (64-bit)

Describe de problem depth:

Autofill of phone number on firefox attempts to insert a +1 in front of a phone number, and it will not insert into the field due to the mask being (999) 999-9999. It is important to call out that I am not adding this +1 to my phone number in firefox addresses, the browser seems to insert this on its own, as I have synced my chrome settings and this is not on my address in chrome. Do you have any suggestions on how to get around this?

osmanybg commented 4 years ago

So whats the problem with the browser attempt to insert the +1? The whole auto complete value is not working for you?

I had a similar issue, in my case, the biggest problem was that the number was cut at 10 digits, so the final digits of the number were lost when they started by 1 or +1 in the autocomplete.

The workaround here was to listen to the "input" event of the input field and do some value sanitation - like trimming the +1 in my case - and then assign the new value to the input field.

Here is an example:

    $('#phone').on('input', on10DigitPhoneInputChange);
    $('#phone').mask('(000) 000-0000');

    function on10DigitPhoneInputChange (e) {
        var $item = $(e.target);
        var value = $item.val();
        var cleanVal = clean10DigitPhone(value);
        var masked = $item.masked(cleanVal);

        $item.val(masked);
    }

    function clean10DigitPhone (phone) {
        var value = phone.replace(/[-\(\)\s]+/g, '');
        var val = trimLeft(value, "+1"); // Trims all '+' and '1' characters form the begining of the string

        return val;
    }

    function trimLeft (from, chars) {
    var c = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    return from.replace(new RegExp("^[" + c + "]+", "g"), "");
    }

You can see a live example here: https://jsfiddle.net/fg4emn5h/2/