Skip to content

Instantly share code, notes, and snippets.

@vitorjustin
Last active September 27, 2022 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitorjustin/2a67673fd31ef9f60f70291327ed30a7 to your computer and use it in GitHub Desktop.
Save vitorjustin/2a67673fd31ef9f60f70291327ed30a7 to your computer and use it in GitHub Desktop.
Máscara para input CPF somente HTML e JS puro
<input type="text" name="cpf" placeholder="CPF" required oninput="cpfMask(this);" pattern="\d{3}\.\d{3}\.\d{3}-\d{2}">
<script>
function cpfMask(i) {
let v = i.value;
let digits = v.replace(/[^0-9]/g, '').substring(0, 11);
let formatted = digits;
formatted = formatted.replace(/^(\d{3})(\d)/, "$1.$2");
formatted = formatted.replace(/^(\d{3})\.(\d{3})(\d)/, "$1.$2.$3");
formatted = formatted.replace(/^(\d{3})\.(\d{3})\.(\d{3})(\d)/, "$1.$2.$3-$4");
i.value = formatted;
return;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment