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.
Hello everyone,
I tried to implement the features presented here, but they are already deprecated, and I am not able to adapt to the new widget, can anyone help me?
I managed to implement it here and it worked, in the React application:
Assign CPF
Substr(Cliente.Identificador,0,3) + "." + Substr(Cliente.Identificador,3,3) + "." + Substr(Cliente.Identificador,6,3) + "-" + Substr(Cliente.Identificador,9,2)
Assign CNPJ
Substr(Cliente.Identificador,0,2) + "." + Substr(Cliente.Identificador,2,3) + "." + Substr(Cliente.Identificador,5,3) + "/" + Substr(Cliente.Identificador,8,4) + "-" + Substr(Cliente.Identificador,12,2)
I used the Substr function to format the value received in my variable, which in the example is Customer.Identifier
Hope it helps someone.