JavaScript Text Only Input

This function can be used on the onkeypress event of a HTML input box to only allow entry of text charactes: A-Z, a-z, dash, space, and backspace.

Usage:

<input type="text" id="name" onkeypress="return textonly(event);" /> 

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);
//alert('Character was ' + character);
    //alert(code);
    //if (code == 8) return true;
    var AllowRegex  = /^[\ba-zA-Z\s-]$/;
    if (AllowRegex.test(character)) return true;    
    return false;
}

6 Responses to JavaScript Text Only Input

  1. christo says:

    Very helpfull!!! Exactly what i was looking for.

  2. Snappit says:

    Thanks.. really help.. !! good job

  3. Samuel says:

    Thanks, just what I needed:)

  4. John says:

    Nice, thanks!

  5. Srinivasan says:

    Thank you boss it’s very helpful.

  6. John says:

    Thanks :D
    it helps me :D

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: