[Custom Input Masks] [Tip] Dynamically switching between CPF and CNPJ masks (Brazilian tax numbers)

Forge Component
(43)
Published on 9 Mar by Marcelo Ferreira
43 votes
Published on 9 Mar by Marcelo Ferreira

Hi all,


Just wanted to share a snippet that allows for dynamically changing the masking format of a given text input from CPF to CNPJ and vice-versa, depending on the length of the typed string.


Here's what it looks like:



This script uses the CPF mask up until the 11th digit. Once the user hits more than 11 digits, the mask is automatically switched to CNPJ.


This is all JavaScript so no Ajax Refreshes nor server requests are needed.


Just create a regular MaskText widget, leave the MaskDefinition empty and paste the following code in the AdvancedOptions field. Remember to replace the "CPF_CNPJInput" reference to the real name of your input.


"{
    mask: function() {
        var nodeId = '" + CPF_CNPJInput.Id + "';
        var cpfMask = '999.999.999-99[999]';
        var cnpjMask = '99.999.999/9999-99';
        var mask = cpfMask;
        var callback = function() {
            var node = document.getElementById( nodeId );
            if ( node && node.value ) {
                node.value = node.value.replace( /[^\d]/g, '' );
                mask = node.value.length > 11 ? cnpjMask : cpfMask;
            }
            setTimeout( updateMask, 0 );
        };
        var updateMask = function() {
            OSPage_InputMaskText( '#' + nodeId, mask, options, 'False' );
        };
        var options = {
            jitMasking: true,
            autoUnmask: true,
            oncomplete: callback,
            onincomplete: callback
        };
        callback();
        return mask;
    }
}"



I hope this helps to improve UX on your Brazilian forms! :-)

Great Tip, Caio!

Thanks, Caio!

I would also like to disclose this module to anyone using the React version.

https://www.outsystems.com/forge/component-overview/7798/mask-br-react

 It also has this mask for CPF and CNPJ.

Thanks for sharing.