views:

70

answers:

3

How can I prevent the user from entering anything but alpha characters in my textbox?

Update Forgot to mention that its a dynmic control (created on the form when the user clicks a button).

A: 

The AjaxControlToolkit has a FilteredTextBox extender that allows you to specify a combination of both lower- and uppercase letters.

PhilPursglove
+1  A: 

With built-in ASP.NET features only, you could use the <asp:RegularExpressionValidator> control, with a regular expresion like [A-Za-z]*. This will validate on server side (which should be your main concern), and give a user-friendly error message on postback. There are ways to use these controls for clientside validation as well if you're using the MVC framework, but I don't know how or how well that works in WebForms.

Using jQuery, there are endless possibilities for clientside validation as well with the jquery.validation plugin.

Tomas Lycken
Client side validation works perfectly in WebForms, the RegularExpressionValidator will validate the field and prevent the form being submitted.
Ben Robinson
@Ben: good then - the more useful is my answer! =)
Tomas Lycken
but its a dynamic control. How would I put a regularExpressionValidator on a control that doesn't exist at design time. What would be the "controlToValidate" ?
user279521
@user279521: In that case, you're probably better off with the jQuery library and its validation plugin: http://www.jquery.com http://plugins.jquery.com/project/jqueryvalidate
Tomas Lycken
A: 

I would set a CssClass on the dynamically created textbox, then use jQuery and some custom javascript/regex to filter any input field with that CssClass on the keyup event.

The filtered TextBox extender is good, and you could probably use that as well, for me, the jQuery solution would be a little easier and flexible.

Jerzakie