Created
December 26, 2012 16:10
-
-
Save tonysm/4381132 to your computer and use it in GitHub Desktop.
Validação de campos numéricos (sem jQuery). Incluindo controle de control C e control V (copy and paste)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>JS Validation</title> | |
<script src="jsvalidation.js"></script> | |
</head> | |
<body> | |
<h1>Validação de números</h1> | |
<p>Detalhe: não é possível também copiar e colar strings no campo, apenas números</p> | |
<label for="numericField">Com validação</label> | |
<input if="numericField" type="text" numeric placeholder="com validação"> | |
<br> | |
<label for="notNumericField">Sem validação</label> | |
<input if="notNumericField" type="text" placeholder="sem validação"> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(window, document, undefined) { | |
"use strict"; | |
/** | |
* cancela o evento | |
* cross-browser | |
* | |
* @param Event event evento a ser cancelado | |
*/ | |
function cancelEvent( event ) { | |
return (event.preventDefault) ? event.preventDefault() : event.returnValue = false; | |
} | |
/** | |
* evento que será adicionado aos campos numericos no evento | |
* keypress | |
* | |
* @param Event event evento keypress | |
*/ | |
function onKeyPressNumericField( event ) { | |
// converte o valor da tecla que está sendo pressionada | |
var k = String.fromCharCode(event.which); | |
// se não for um numero | |
if(!(!isNaN(k) && isFinite(k))) { | |
cancelEvent(event); | |
} | |
} | |
/** | |
* evento que será atribuido aos campos numeric no evento paste | |
* | |
* @param Event event evento paste | |
*/ | |
function onPasteNumericField( event ) { | |
// pega o clipboard do usuário (onde estão os valores do CTRL+C e CTRL+V) | |
var clipBoard = (event.clipboardData !== undefined) ? | |
event.clipboardData : window.clipboardData, | |
// pega o valor que está sendo colado | |
pastedValue = clipBoard.getData('Text'), | |
// regra de validação de numeros | |
regex = /^\d+$/; | |
// se não for numero, cancela o evento (impossibilidando colar o valor) | |
if(!regex.test(pastedValue)) { | |
cancelEvent(event); | |
} | |
} | |
/** | |
* quando concluir o carregamento da página | |
*/ | |
window.addEventListener('load', function() { | |
// buscando todos os inputs que possuim o atributo numeric | |
var inputs = document.querySelectorAll('input[numeric]'), | |
// quantidade de inputs com esse atributo | |
inputsLen = inputs.length; | |
// para cada input com esse atributo | |
for(var i = 0; i < inputsLen; i++) { | |
// cache do input | |
var inpt = inputs[i]; | |
// atribuindo os eventos | |
inpt.addEventListener('keypress', onKeyPressNumericField); | |
inpt.addEventListener('paste', onPasteNumericField); | |
} | |
}); | |
})(window,document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment