0
What I want to do is: type a CPF without dots or dash and then add the dots and dash with JS, create a pattern. Example: I write 99999999 and the system returns 999.999.999-99. How do I do this in pure Javascript?
0
What I want to do is: type a CPF without dots or dash and then add the dots and dash with JS, create a pattern. Example: I write 99999999 and the system returns 999.999.999-99. How do I do this in pure Javascript?
6
You can use Regular Expressions. Ex:
^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$
└───┬───┘└───┬───┘└───┬───┘└───┬───┘
│ │ │ └───── Captura os dois últimos dígitos
│ │ └────────────── Captura os valores entre 7º e 9º dígitos
│ └─────────────────────── Captura os valores entre o 4º e 6º dígito
└──────────────────────────────── Captura o três primeiros dígitos
Then just use: $1
, $2
, $3
and $4
to capture the groups.
Following example:
const cpf = document.querySelector("#cpf");
cpf.addEventListener("blur", () => {
let value = cpf.value.replace(/^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/, "$1.$2.$3-$4");
cpf.value = value;
});
<input type="text" value="" id="cpf" />
You can also use the event keyup
to do this while typing text.
const cpf = document.querySelector("#cpf");
cpf.addEventListener("keyup", () => {
let value = cpf.value.replace(/[^0-9]/g, "").replace(/^([\d]{3})([\d]{3})?([\d]{3})?([\d]{2})?/, "$1.$2.$3-$4");
cpf.value = value;
});
<input type="text" value="" id="cpf" />
I’m studying JS so this kind of help is sensational. Thank you so much!
The keyup is terrible for editing the number. In this second case, I recommend letting the user type only digits, and put the dots and dash only after (try typing a wrong character or two and correct). But the answer is ok, it’s already taken my +1
I removed the syntax highligther from the diagram (I couldn’t resist and I took the liberty of switching to box characters, if you don’t like it, feel free to reverse it, just notice the HTML Comment that takes the color out of the snippet. (Then I delete this comment here)
I have been looking for a while for regex js and did not understand how it worked until I found this wonderful answer and show how simple it is!
0
Another way using regex:
var cpf = document.querySelector("#cpf");
cpf.addEventListener("blur", function(){
cpf.value = cpf.value.match(/.{1,3}/g).join(".").replace(/\.(?=[^.]*$)/,"-");
});
<input type="text" id="cpf" maxlength="11" />
A regex /.{1,3}/g
breaking the 3-character string creating an array. o join(".")
re-joins the array by inserting a point between each item, and the replace
with the regex /\.(?=[^.]*$)/
replaces the last point ".
" hyphenated "-
".
Browser other questions tagged javascript html
You are not signed in. Login or sign up in order to post.
Possible duplicate of Regular expression to validate a field that accepts CPF or CNPJ
– NoobSaibot