How to make mask for display phone, cnpj, Cpf, etc on Laravel

Asked

Viewed 6,043 times

1

Show 1 more comment

1 answer

3

Well, as you want to display, then you have two options:

  • Format the value before sending to view;
  • Format the value in the view using JS.

To format using PHP the code you have shown should already serve. 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 JS library, I recommend Inputmaskjs: https://github.com/RobinHerbots/Inputmask

You put Cpf, cnpj or phone in an input and then call the library method to apply any mask. On the github link above there are a number of examples you can follow.

  • And to validate the data in the back-end I recommend using this lib: https://github.com/geekcom/validator-docs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.