Skip to content

Instantly share code, notes, and snippets.

@devLopez
Created September 16, 2020 19:12
Show Gist options
  • Save devLopez/b3575cdcaaeaf9728c143d0789ef0e8c to your computer and use it in GitHub Desktop.
Save devLopez/b3575cdcaaeaf9728c143d0789ef0e8c to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="pt-BR" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<form method="post" action="autentica.php">
<fieldset>
<legend>Usuário</legend>
<input type="text" name="txtUsuario" id="usuario"> <br>
</fieldset>
<fieldset>
<legend>Senha</legend>
<input type="password" name="txtSenha">
</fieldset>
<br>
<button type="submit">
Enviar
</button>
</form>
<script type="text/javascript">
let tokens = {
'#': {pattern: /\d/},
'X': {pattern: /[0-9a-zA-Z]/},
'S': {pattern: /[a-zA-Z]/},
'A': {pattern: /[a-zA-Z]/, transform: v => v.toLocaleUpperCase()},
'a': {pattern: /[a-zA-Z]/, transform: v => v.toLocaleLowerCase()},
'!': {escape: true}
};
function maskit (value, mask, masked = true, tokens) {
value = value || ''
mask = mask || ''
var iMask = 0
var iValue = 0
var output = ''
while (iMask < mask.length && iValue < value.length) {
var cMask = mask[iMask]
var masker = tokens[cMask]
var cValue = value[iValue]
if (masker && !masker.escape) {
if (masker.pattern.test(cValue)) {
output += masker.transform ? masker.transform(cValue) : cValue
iMask++
}
iValue++
} else {
if (masker && masker.escape) {
iMask++ // take the next mask char and treat it as char
cMask = mask[iMask]
}
if (masked) output += cMask
if (cValue === cMask) iValue++ // user typed the same char
iMask++
}
}
// fix mask that ends with a char: (#)
var restOutput = ''
while (iMask < mask.length && masked) {
var cMask = mask[iMask]
if (tokens[cMask]) {
restOutput = ''
break
}
restOutput += cMask
iMask++
}
return output + restOutput
}
function event (name) {
var evt = document.createEvent('Event')
evt.initEvent(name, true, true)
return evt
}
let usuario = document.getElementById('usuario');
usuario.oninput = function (evt) {
if (!evt.isTrusted) return // avoid infinite loop
// by default, keep cursor at same position as before the mask
var position = usuario.selectionEnd
// save the character just inserted
var digit = usuario.value[position-1]
usuario.value = maskit(usuario.value, '###.###.###-##', true, tokens)
// if the digit was changed, increment position until find the digit again
while (position < usuario.value.length && usuario.value.charAt(position-1) !== digit) {
position++
}
if (usuario === document.activeElement) {
usuario.setSelectionRange(position, position)
setTimeout(function () {
usuario.setSelectionRange(position, position)
}, 0)
}
usuario.dispatchEvent(event('input'))
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment