sábado, 18 de diciembre de 2010

JavaScript - Validar ingreso de texto

Si qusieramos validar que sólo se ingrese texto lo hacemos con la siguiente función:


<html>
<body>

<script type="text/javascript">

function textonly(e){
var code;

if (!e) var e = window.event;
if (e.keyCode)
code = e.keyCode;
else
if (e.which)
code = e.which;
var character = String.fromCharCode(code);
var AllowRegex = /^[\ba-zA-Z\s-]$/;
if (AllowRegex.test(character)) return true;
return false;
}

</script>

<td width="15%">Ingrese solo texto </td>
<input name="nombre" size="30" onkeypress="return textonly(event);"/>

</body>
</html>


Hay un sitio muy interesante donde podemos probar nuestro código.
Vaya a http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro y pegue en la parte izquierda cualquiera de los ejemplos aquí presentados, a continuación haga click en Edit and Click Me.

JavaScript - Validar ingreso de numeros

Validar que solo se ingresen numeros en un input:

<html>
<body>

<script type="text/javascript">

function numbersonly(myfield, e, dec){

var key;
var keychar;

if (window.event)
key = window.event.keyCode;

else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}


</script>

<td width="15%">Ingrese solo numeros </td>
<input name="nombre" size="30" onkeypress="return numbersonly(this,event);"/>

</body>
</html>