Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

asp.net - Textbox with alphanumeric check in javascript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...