how to use RegularExpressionValidator on textbox

happysmile picture happysmile · Jan 20, 2011 · Viewed 59.3k times · Source

I have an text box i need to validate so that the user can enter enter up to four character and they can be alphanumeric. I am using VS2003, .NET 1.1.

Please let me know what is the expression i should use to validate this condition any help would be great. Thanks!

Tried like this:

<asp:TextBox id="wtxtTPP" tabIndex="2" runat="server" CssClass="text" Width="144px" MaxLength="4" />
<asp:RegularExpressionValidator id="RegularExpressionValidator1" style="z-index: 101; left: 208px; position: absolute; TOP: 16px" runat="server" ErrorMessage="RegularExpressionValidator" ValidationExpression="^([\S\s]{0,4})$" ControlToValidate="wtxtTPP" />
<input style="z-index: 102; left: 88px; position: absolute; top: 72px" type="submit" value="Submit" id="Submit1" name="Submit1" runat="server">

Answer

Remy picture Remy · Jan 20, 2011

As you said, use a Regular Expression Validator and set the expression to something like this:

^([\S\s]{0,4})$

Replace the 4 with your desired max length.

Update:

<asp:TextBox id="wtxtTPP" Runat="server" />

<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" 
        ErrorMessage="RegularExpressionValidator" 
        ValidationExpression="^([\S\s]{0,4})$" 
        ControlToValidate="wtxtTPP" />

<asp:Button ID="Button1" runat="server" Text="Button" />

This works just fine for me. I replaced your submit button with a normal asp.net button and simplified out all the unneeded stuff for the example.
In general, if you only have a one line textbox, you can just limit the text length with MaxLength="4" as you did. No need for a Validator.