开发者

How to allow only English (A-Z) characters to be typed into a textbox?

开发者 https://www.devze.com 2022-12-24 18:44 出处:网络
I want to allow only English c开发者_Go百科haracters to be typed in my asp:TextBox (in asp:Login control).

I want to allow only English c开发者_Go百科haracters to be typed in my asp:TextBox (in asp:Login control).

How can I do that?


If you want to validate the input

Use a RegularExpressionValidator control. There is a decent example and explanation at How To: Use Regular Expressions to Constrain Input in ASP.NET.

The regular expression for only English (upper and lower case A-Z) characters is ^[A-Za-z]*$

If you want to include numbers too, ^[A-Za-z0-9]*$

Snippet of the markup you'll want to add:

<asp:RegularExpressionValidator ID="regexpName" runat="server"     
      ErrorMessage="Only upper and lower case A-Z may be entered here." 
      ControlToValidate="txtInput"     
      ValidationExpression="^[A-Za-z]*$" />

If you want to prevent a user from typing anything else into the box

You're better off using the jQuery script in the answer to this question: how do i block or restrict special characters from input fields with jquery?

BUT you are always going to want to validate the input too, (what if the user turns off JavaScript for example), so use the validation method described above as well.


You can achieve this using the FilteredTextBox.

It can also be done with plain javascript (FilteredTextBox also relies on javascript, but you can do it with only javascript that you write yourself) by registering an onKeyUp listener, and filtering out the characters that are not in an allowed subset (perhaps with a regex replace)

0

精彩评论

暂无评论...
验证码 换一张
取 消