How to receive the CPF number and format to be without the dots and dash(Input Mask )

Asked

Viewed 7,167 times

2

I’m creating a mask with inputMask, but the number is received so: 222.222.488-19.

And I want him to have the mask on input but when sending it will be without the dots and the dash. Like this 22222248819. My code:

@Component({
  selector: 'app',
  template: `
    <input [textMask]="{mask: mask}" [(ngModel)]="myModel" type="text"/>
  `
})
export class AppComponent {
  public myModel = ''
  public mask = ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
}

7 answers

3

    var variavel=$("#campo").val();//atribui o valor a variavel
    var variavel2 = variavel.replace('.', ''); //remove UM ponto
  var variavel2 = variave2.replace(',', ''); //remove UMA virgula
  var variavel2 = variave2.replace('-', ''); //remove UM traço

BELOW VAII EXPLAINED

$(document).ready(function(){
$('.cpf').mask('000.000.000-00', {reverse: true});
  $('.cnpj').mask('00.000.000/0000-00', {reverse: true});
  $('.dinheiro').mask('000.000,00', {reverse: true});
 
 
$("#Botao").on("click", function(e){
e.preventDefault(e);

//Variavel com valor do campo dinheiro
var dinheiro=$("#dinheiro").val();
//retira o ponto coloca o restante em dinheiro 2.
var dinheiro2 = dinheiro.replace('.', '');
//retirar a virgula, e colocar o restante na dinheiro2.
var dinheiro2 = dinheiro2.replace(',', '');
//RECUPERAR VALORES do dinheiro.
alert(" O DINHEIRO COM MASCARA FOI : " +dinheiro+ " O DINHEIRO SEM MASCARA È: "+dinheiro2);
//Variavel com valor do campo cnpj
var cnpj=$("#cnpj").val();
var cnpj2 = cnpj.replace('.', '');
var cnpj2 = cnpj2.replace('.', '');
//*se tiver 1 ponto, dá um replace no ponto. se tiver 10... dá 10 replace.
var cnpj2 = cnpj2.replace('-', '');
var cnpj2 = cnpj2.replace('/', '');
//RECUPERAR VALORES do dinheiro.
alert(" O CNPJ COM MASCARA FOI : " +cnpj+ " O CNPJ SEM MASCARA È: "+cnpj2);

//Variavel com valor do campo CPF
var cpf=$("#cpf").val();
var cpf2 = cpf.replace('.', '');
var cpf2 = cpf2.replace('.', '');
//*se tiver 1 ponto, dá um replace no ponto. se tiver 10... dá 10 replace.
var cnpj2 = cnpj2.replace('-', '');
//RECUPERAR VALORES do dinheiro.
alert(" O CPF COM MASCARA FOI : " +cpf+ " O DO CPF SEM MASCARA È: "+cpf2);

})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<!-- ENTENDA OS CAMPOS PELO ID. é o id que vaos usar para recuperar os valores.-->
    <input class="dinheiro" id="dinheiro" placeholder="DIGITE UM VALOR EM DINHEIRO">
    <input class="cnpj" id="cnpj" placeholder="DIGITE UM CNPJ">
    <input class="cpf" id="cpf" placeholder="DIGITE UM CPF">
   <br>
     <br>
       <br>
 PREENCHA TODOS OS CAMPOS E <br>
<button type="" id="Botao">CLIQUE AKI</button>
 <!-- PULE PARA O EVENTO JAVASCRIPT-->

  • If this solves your problem, mark as answered.

2

Just to supplement the previous answers. If you want to take both at once (dot and dash). My answer is with Pure JS.

let botao = document.querySelector("#botao");

botao.onclick = function() {
  let cpf_com_ponto_e_traco = document.querySelector("#cpf-com-ponto-e-traco").value;
  let cpf_sem_ponto_e_traco = cpf_com_ponto_e_traco.replace(".", "").replace(".", "").replace("-", "");

  console.log(cpf_sem_ponto_e_traco);
}
<input type="text" id="cpf-com-ponto-e-traco" value="111.222.333-44" readonly>
<button id="botao">Pegar CPF</button>

And another alternative to not having to use twice the replace to take out the first two points and replace to take out the trace. To do this we use a regular expression in the first parameter of replace which only allows alphanumeric characters in that string. What is not a number, the replace exchange for second parameter. Behold:

let botao = document.querySelector("#botao");

botao.onclick = function() {
  let cpf_com_ponto_e_traco = document.querySelector("#cpf-com-ponto-e-traco").value;
  let cpf_sem_ponto_e_traco = cpf_com_ponto_e_traco.replace(/[^0-9]/g, "");

  console.log(cpf_sem_ponto_e_traco);
}
<input type="text" id="cpf-com-ponto-e-traco" value="111.222.333-44" readonly>
<button id="botao">Pegar CPF</button>

  • finally an answer with the code clean and no dependency of libraries not cited by OP, I recommend only adapt pro case of Cpf’s with 2 point Replaces, but very good. + 1

  • Do you believe that I had made the answer thinking of cep ? But I have corrected.

1

Follows a solution with regex, where you don’t need to be doing several places, it will capture only the digits in a array and convert them into a string with the function Join.

Example:

let botao = document.querySelector("#botao");

botao.onclick = function() {

  let valorOriginal = document.querySelector("#cpf").value;
  let regex = /\d/g;
  let valorFiltrado = valorOriginal.match(regex);
  
  console.log(valorFiltrado.join(""));
}
<input type="text" id="cpf" value="455.666.727-99" readonly>
<button id="botao">Submit</button>

For those who love solutions in a row:

console.log("455.546.727-47".match(/\d/g).join(""));

Explanation

  • We get the Cpf field value with the query selector and assign it to the variable valorOriginal
  • Then we declare the regex variable with the value /\d/g;
    The first / shows for javascript that we are declaring a regular expression type variable
    The \d then represents what we want to capture, a digit.
    We close the regex declaration with the /
    And finally we put the g, signaling that this regex must traverse the entire string.
  • Next we will use the function match to return what regex captures as an Array.
  • And to display the value as a string we use the function join(""), it will return all our values in a string without separation by comma, as it would normally if we used only the function toString().

1

var cpf = '000.000.000-00';
var string = cpf.replace('.','').replace('-','').replace('.','') ;
  • By the way, I recommend testing your answer again, it does not answer the question correctly, beware in detail: but when sending will be without the dots and the dash. Type this 22222248819... Your answer only takes 1 of the dots.

  • edited my reply @Paz

  • now yes, sometimes these details catch us.

1

Creates a function that removes these characters using regexp there in Mask. For example:

function somenteNumeros(cpf){
  let numeros = cpf.toString().replace(/\.|-/gm,'');
  if(numeros.length === 11)
   return numeros;

  return 'cpf inválido'
 }

 export class AppComponent {
   public myModel = ''
   public mask = somenteNumeros(cpf)
 }

if you need to do several regex tests, recommend the site: https://regex101.com/

0

You can do it directly in your form before submitting it through replace():

formulario: FormGroup; this.formulario.value.cpf = this.formulario.value.cpf.replace(/\.|-/gm,'');

Obs.: whereas your formControlName="Cpf".

0

In JS has the function replace().
You can do something like cpfComMascara.replace("\D", "")
In regex \d means digit. The uppercase letter is the opposite.
Therefore, regex will replace non-digit with empty.

Browser other questions tagged

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