Uma necessidade bem comum em sistemas comerciais voltados para web é a validação/consistência de valores inseridos em campos ou controles. Porém, como sabemos, os controles HTML e seu contexto são bem, digamos, “traiçoeiros”.
Não temos neles toda a riqueza de uma interface gráfica ou um controle efetivo de seus eventos. Mas como o Javascript tem se tornado cada vez mais indispensável na construção desses sistemas, mesmo não tendo que sê-lo, nada como apelar para ele em casos como esse.
A função disponibilizada abaixo garante por meio do onkeydown evento Javascript que somente valores numéricos sejam digitados em um campo texto.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
| /*
* função para permitir a digitação de números decimais e inteiros
*/
function ForceNumericInput(event, This, AllowDecimal, AllowMinus)
{
if(arguments.length == 1)
{
var s = This.value;
// garante que o sinal de "-" seja o primeiro do índice
var i = s.lastIndexOf("-");
if(i == -1)
return;
if(i != 0)
This.value = s.substring(0,i)+s.substring(i+1);
return;
}
switch(event.keyCode)
{
case 8: // backspace
case 9: // tab
case 37: // left arrow
case 39: // right arrow
case 46: // delete
event.returnValue = true;
return;
}
if(event.keyCode == 189) // sinal de número de negativo
{
if(AllowMinus == false)
{
CancelEventExecution(event);
return;
}
// aguarda até que o controle tenha sido atualizado
var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
setTimeout(s, 250);
return;
}
if(AllowDecimal && event.keyCode == 188)
{
if(This.value.indexOf(",") >= 0)
{
// restringe a digitação de apenas uma vírgula
CancelEventExecution(event);
return;
}
event.returnValue = true;
return;
}
// permite caracteres entre 0 e 9
if(event.keyCode >= 48 && event.keyCode <= 57)
{
event.returnValue = true;
return;
}
CancelEventExecution(event);
}
/*
* Cancela a execução de uma function mapeada por um evento
*/
function CancelEventExecution(event)
{
if (navigator.appName == "Netscape")
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
} |
/*
* função para permitir a digitação de números decimais e inteiros
*/
function ForceNumericInput(event, This, AllowDecimal, AllowMinus)
{
if(arguments.length == 1)
{
var s = This.value;
// garante que o sinal de "-" seja o primeiro do índice
var i = s.lastIndexOf("-");
if(i == -1)
return;
if(i != 0)
This.value = s.substring(0,i)+s.substring(i+1);
return;
}
switch(event.keyCode)
{
case 8: // backspace
case 9: // tab
case 37: // left arrow
case 39: // right arrow
case 46: // delete
event.returnValue = true;
return;
}
if(event.keyCode == 189) // sinal de número de negativo
{
if(AllowMinus == false)
{
CancelEventExecution(event);
return;
}
// aguarda até que o controle tenha sido atualizado
var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
setTimeout(s, 250);
return;
}
if(AllowDecimal && event.keyCode == 188)
{
if(This.value.indexOf(",") >= 0)
{
// restringe a digitação de apenas uma vírgula
CancelEventExecution(event);
return;
}
event.returnValue = true;
return;
}
// permite caracteres entre 0 e 9
if(event.keyCode >= 48 && event.keyCode <= 57)
{
event.returnValue = true;
return;
}
CancelEventExecution(event);
}
/*
* Cancela a execução de uma function mapeada por um evento
*/
function CancelEventExecution(event)
{
if (navigator.appName == "Netscape")
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
}
Para aplicar a função em um controle input, as opções seriam as seguintes:
Para permitir a digitação de números inteiros de decimais positivos ou negativos
1
2
| <input type="text" name="TextBoxNumeric" id="TextBoxNumeric" value=""
onkeydown="ForceNumericInput(event, this, true, true)" /> |
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric" value=""
onkeydown="ForceNumericInput(event, this, true, true)" />
Para permitir a digitação de inteiros positivos ou negativos
1
2
| <input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, false, true)" /> |
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, false, true)" />
Para permitir a digitação de inteiros e decimais positivos
1
2
| <input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, true, false)" /> |
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, true, false)" />
Para permitir a digitação de somente inteiros positivos
1
2
| <input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, false, false)" /> |
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
value="" onkeydown="ForceNumericInput(event, this, false, false)" />
A função acima tem como base um exemplo postado no site CodeProject (http://www.codeproject.com/KB/scripting/JavaScriptForceNumInput.aspx), porém, com a limitação de funcionar apenas no Internet Explorer.
Foram aplicadas algumas correções como a permissão de navegar por meio da tecla TAB, o que não estava previsto na função original. A função CancelEventExecution foi criada para garantir o cancelamento da execução do evento em navegadores não Internet Explorer. também foi necessário adicionar o parâmetro event, que é implícito no nvagedor da Microsoft, mas precisa ser informada nos demais.
Com isso, a função passar a funcionar corretamente na maior parte dos navegadores.
Aplicando ao função no ASP.NET
Abaixo segue um pequeno exemplo de como aplicar esta função a um controle TextBox no ASP.NET:
1
2
3
| TextBox.Attributes.Add("onkeydown", string.Format(
"ForceNumericInput(event, this, {0}, {1});",
true.ToString().ToLower(), true.ToString().ToLower())); |
TextBox.Attributes.Add("onkeydown", string.Format(
"ForceNumericInput(event, this, {0}, {1});",
true.ToString().ToLower(), true.ToString().ToLower()));
Abraços
Tomás