Sei sulla pagina 1di 4

<script>

function validarNro(e) {
var key;
if(window.event) // IE
{
key = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
key = e.which;
}

if (key < 48 || key > 57)


{
if(key == 46 || key == 8) // Detectar . (punto) y backspace (retroceso)
{ return true; }
else
{ return false; }
}
return true;
}
</script>

2. En el campo de texto que quieras validar / restringir agregar el evento


onkeypress para llamar a la funcin:
<input type="text" name="textfield" id="textfield"
onkeypress="javascript:return validarNro(event)" />

Cdigo completo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Validar textobox que reciba solo nmeros</title>

<script language="javascript">

function validarNro(e) {

var key;

if(window.event) // IE

key = e.keyCode;

else if(e.which) // Netscape/Firefox/Opera

key = e.which;

if (key < 48 || key > 57)

if(key == 46 || key == 8 ) // Detectar . (punto) y backspace (retroceso)

{ return true; }
else
{ return false; }

return true;

</script>

</head>

<body>

<p><strong>Validar textbox que reciba solo nmeros</strong><br />

<a href="http://blog.nicolasmendez.com.ar">blog.nicolasmendez.com.ar</a>

<form id="form1" name="form1" method="post" action="">

<input type="text" name="textfield" id="textfield"


onkeypress="javascript:return validarNro(event)" />

</form>

</p>

</body>

</html>

Potrebbero piacerti anche