Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  76] [ 4]  / answers: 1 / hits: 22920  / 15 Years ago, thu, june 4, 2009, 12:00:00

I have a textbox, and it needs not allow the user to enter any special characters. He can enter:




  1. A-Z

  2. a-z

  3. 0-9

  4. Space.



One more condition is the first letter should be alphabetic.
How can I do a JavaScript verification on each keypress?


More From » asp.net

 Answers
29

add a onKeyUp=javascript:checkChar(this); to the input box.



function checkChar(tBox) {   

var curVal = tBox.value;

if ( /[^A-Za-z0-9 ]/.test(curVal) ) {

//do something because he fails input test.

}

}


alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:



onKeyUp=javascript:checkChar(event);



function checkChar(e) {

var key;


if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;

if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {

//fails test

}

}


missed the part about first char, but you can do a test on the textbox value as in the first example:



/^[A-Za-z]/.test(curVal)


or even use the second method but pass the text box as well so you can get it's full value.


[#99383] Monday, June 1, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;