Skip to content

Instantly share code, notes, and snippets.

@viniceosm
Last active May 29, 2020 15:16
Show Gist options
  • Save viniceosm/c82ac216b53a74b167c9899b27a8e8a0 to your computer and use it in GitHub Desktop.
Save viniceosm/c82ac216b53a74b167c9899b27a8e8a0 to your computer and use it in GitHub Desktop.

Função JS

function maskVini() {
    var inputsMascara = document.querySelectorAll('[mask-vini]');
    
    inputsMascara.forEach((inputMascara) => {
        inputMascara.addEventListener('input', (event) => {
            var padraoMascara = inputMascara.getAttribute('mask-vini');
            mask(inputMascara, padraoMascara, event);
        }, false);
    });

    function mask(input, mask, evt) {
        try {
            var value = input.value;

            // If user pressed DEL or BACK SPACE, clean the value
            try {
                var e = (evt.which) ? evt.which : event.keyCode;
                if (e == 46 || e == 8) {
                    input.value = "";
                    return;
                }
            } catch (e1) { }

            var literalPattern = /[0\*]/;
            var numberPattern = /[0-9]/;
            var newValue = "";

            for (var vId = 0, mId = 0; mId < mask.length;) {
                if (mId >= value.length)
                    break;

                // Number expected but got a different value, store only the valid portion
                if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
                    break;
                }

                // Found a literal
                while (mask[mId].match(literalPattern) == null) {
                    if (value[vId] == mask[mId])
                        break;

                    newValue += mask[mId++];
                }

                newValue += value[vId++];
                mId++;
            }

            input.value = newValue;
        } catch (e) { }
    }
};

Código HTML

Depois de criar o input deverá executar a função. Pode fazer no evento onload.

0 Para digitos numerais
<input type="text" id="txtAlgo" mask-vini="0000.000.0000.0000" />

<script>
    maskVini();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment