Skip to content

Instantly share code, notes, and snippets.

@jeovazero
Last active May 14, 2019 02:12
Show Gist options
  • Save jeovazero/659db30b8d7ba6f8f49715e95911270d to your computer and use it in GitHub Desktop.
Save jeovazero/659db30b8d7ba6f8f49715e95911270d to your computer and use it in GitHub Desktop.
function cpfMask(e){
var value = e.target.value
var separatorList = [[3, '.'], [3, '.'], [3, '-'], [2, '']]
var clean = value.replace(/[^\d]/g, "").substr(0, 11)
var value2 = ""
var index = 0
for(var i = 0; i < separatorList.length; i++){
var separator = separatorList[i][1]
var len = separatorList[i][0]
value2 += clean.substr(index, len)
index += len
if(clean.length >= index) value2 += separator
else break
}
e.target.value = value2
}
function applyCpfMask(selector){
var input = document.querySelector(selector)
input.placeholder="000.000.000-00"
input.type = "text"
input.onkeyup = cpfMask
}
// Apply
applyCpfMask('input[name=cpf]')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment