Introduction
This is a single way to implement a character restriction in a page. Using this Javascript we can to restrict the input characters in a specific way for each control textbox.
Javascript Code
The code is simple, a getkeycode(event) returns the javascript keycode or event.which, depends on the browser.
function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
And a keyRestrict(event, validcharacters_string) returns a true or false if the key pressed is a valid character or not.
function keyRestrict(e, validchars) {
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}
Implementation
To use this is simple, just put a function call in the onkeypress event of the textbox
Numeric sample:
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'1234567890')">
Alfa (not alfanumeric just alfa in this case accepts a SPACE)
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'abcdefghijklmnopqrstuvwxyz ')">
Ñ support (spanish keyboards for example).
Here a sample with the Ñ support. because if you type the 'ñ' in the string the script fail in the moment you press the ñ char.
to have Ñ suport we need to put the next code:
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'abcdefghijklmnopqrstuvwxyz '+String.fromCharCode(241))">
this is a simple script, but the Ñ support is usefull to me, and i wabt to share the solution
Ing. F. Marcelo Lujan alias El Bebe Dot Net. Hola, yo desarrollo de forma independiente en C#. ASP.NET y Win32 Diseño Macromedia etc. con mas de 10 años de experiencia en informática y soporte a sistemas, así como desarrollo de software y nuevos productos.
Espero que ayude la informacion que pongo a su disposicion.
I Hope this information that i upload to codeproject helps you.
Atte: Marcelo Lujan