phalanx
phalanx

Reputation: 497

How to Disable non alphabetic characters in Textbox?

No, I don't mean asp validation controls, I'm looking for a way to "disable" non alphabetic characters, so when user presses any key that is not a letter(except for space), it simply does not be written in the textbox.

Upvotes: 0

Views: 1317

Answers (3)

wweicker
wweicker

Reputation: 4962

There are many ways to do this, but I just thought I'd share a few thoughts in case someone else stumbles upon this question looking for a quick and dirty solution.

Another simple javascript option is to just remove anything you don't want during onKeyUp.

Add the javascript event to your TextBox:

<asp:TextBox ID="txtWhatever" runat="server" onkeyup="javascript:OnKeyUpEvent(this);" />

Then write a simple function with whatever RegEx you want:

function OnKeyUpEvent(txt) {
    txt.value = txt.value.replace(/[\W_]+/g, ""); // Only accept alpha-numeric characters
}

onKeyDown works for simple keycodes but combinations are a problem. Say for example you want to allow numbers but not symbols and a user holds SHIFT then presses 4. That triggers onKeyDown twice, once with keyCode 16 (SHIFT key) and once with keyCode 52 (4 key). You might then be left with a "$" in your textbox when you have code in onKeyDown that gives a pass to keyCode == 52.

Another consideration is copy/paste. If a user pastes a long string full of invalid characters this onKeyUp method will strip them all away.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172638

You can try using this:-

ValidationExpression="^[A-Za-z]*$"

or the simple solution using javascript:-

if ((event.keyCode > 64 && event.keyCode < 91) || (event.keyCode > 96 && event.keyCode < 123) || event.keyCode == 8)
   return true;
else
   {
       alert("Please enter only char");
       return false;
   }

Upvotes: 2

Garrison Neely
Garrison Neely

Reputation: 3289

I've always used the AjaxControlToolkit's FilteredTextBoxExtender: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx

Upvotes: 3

Related Questions