Format phone numbers and CNPJ

1

I'm breaking my head on how to display phone numbers and CNPJ formatted through PHP.

My ideas are or create a script that when filling in the dots and dashes are automatically placed (style when you fill in the CPF with numbers only and the site does the punctuation automatically), what language should I use for this?

Or the output that I think is easiest, in the command echo delimiter the punctuation through the length of the string, someone would know to indicate which commands I should use (it may be just a north, tell me which command does this that I go after more information)?

    
asked by anonymous 14.11.2017 / 17:03

2 answers

-1

You can do it in several ways, I'll show you the simplest. There is a library of your own that you can "Import" through the link.

<script type="text/javascript" src="js/jquery.mask.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

addthisscriptbelowinyourHTMLaswell

<scripttype="text/javascript">
    $(document).ready(function(){
      $('#cpf').mask('00000-000');
      $('#cnpj').mask('00.000.000/0000-00');
      $('#telefone').mask('0000-0000');
    });
 </script> 

And in your input just place the ID for what you indicated in JavaScript. But you can also create a class and refer to $('.cpf').mask('00000-000); however, you will have to change its input and instead of putting class='cpf'

<input type='text' name='cpf' id='cpf'>

<input type='text' name='cnpj' id='cnpj'>

<input type='text' name='telefone' id='telefone'>

Remembering that if you want to send directly to the database, in your variables you will have to make a deal to eliminate the points, I will leave a simple example below of how it should be done.

$chars = array(".","/","-", "*"); /* aqui indico os caracteres que desejo remover */

$cpf = str_replace($chars, "", $_POST['cpf']); /* através de str_replace insiro somente os números invés de caracteres */
$cnpj = str_replace($chars, "", $_POST['cnpj']);
$telefone = str_replace($chars, "", $_POST['telefone']);
    
14.11.2017 / 17:23
1

Create a function in jQuery to validate the CPF and / or CNPJ. If it is not something visual only, you will have to do the save treatment in the database, giving .replace in points and slash.

Example:

$(function () {
        $("[id$=txtCpfCnpj]").focusout(function () {
            $(this).unmask();
            $(this).val($(this).val().replace(/\D/g, ""));
        }).click(function () {
            $(this).val($(this).val().replace(/\D/g, "")).unmask();
        }).blur(function () {
            if ($(this).val().length == 11) {
                $(this).mask("999.999.999-99");
            } else if ($(this).val().length == 14) {
                $(this).mask("99.999.999/9999-99");
            }
        });
    });
    
14.11.2017 / 17:12