I'm new to Laravel and would like to display fields like CPF, CNPJ and Headphones formatted as (xx) xxxxx-xxxx, etc.
I researched and found a function that would execute this (mask: link ) but I could not insert it.
I'm new to Laravel and would like to display fields like CPF, CNPJ and Headphones formatted as (xx) xxxxx-xxxx, etc.
I researched and found a function that would execute this (mask: link ) but I could not insert it.
Well, as you want to display, then you have two options:
To format using PHP the code you have already displayed should work. But if you want, take a look at my implementation to apply mask to CPF, CNPJ and Phone (it is taken into account that the value only has numbers):
/**
* Formata uma string segundo a máscara de CPF
* caso o tamanho da string seja diferente de 11, a string será retornada sem formatação
* @param string $cpf
* @return string
*/
function cpf($cpf) {
if (! $cpf) {
return '';
}
if (strlen($cpf) == 11) {
return substr($cpf, 0, 3) . '.' . substr($cpf, 3, 3) . '.' . substr($cpf, 6, 3) . '-' . substr($cpf, 9);
}
return $cpf;
}
/**
* Formata uma string segundo a máscara de CNPJ
* caso o tamanho da string seja diferente de 14, a string será retornada sem formatação
* @param $cnpj
* @return string
*/
function cnpj($cnpj) {
if (! $cnpj) {
return '';
}
if (strlen($cnpj) == 14) {
return substr($cnpj, 0, 2) . '.' . substr($cnpj, 2, 3) . '.' . substr($cnpj, 5, 3) . '/' . substr($cnpj, 8, 4) . '-' . substr($cnpj, 12, 2);
}
return $cnpj;
}
/**
* Formata uma string segundo a máscara de telefone
* caso o tamanho da string seja diferente de 10 ou 11, a string será retornada sem formatação
* @param string $fone
* @return string
*/
function fone($fone) {
if (! $fone) {
return '';
}
if (strlen($fone) == 10) {
return '(' . substr($fone, 0, 2) . ')' . substr($fone, 2, 4) . '-' . substr($fone, 6);
}
if (strlen($fone) == 11) {
return '(' . substr($fone, 0, 2) . ')' . substr($fone, 2, 5) . '-' . substr($fone, 7);
}
return $fone;
}
If you prefer to use a library in JS, I recommend InputmaskJS: link
You put cpf, cnpj or phone in an input and then call the library method to apply any mask. In the github link you put up there are a number of examples you can follow.