Surya sasidhar
Surya sasidhar

Reputation: 30303

Regular expression validation (should start with character )

In my web application, I have a text box.

The user should enter a value of which the first character is a letter, not a digit, and the remaining characters can be alphanumeric.

How can I write regular expression to do this?

Upvotes: 0

Views: 6950

Answers (2)

Rex M
Rex M

Reputation: 144112

<asp:TextBox id="TextBox1" runat="server"/>
<asp:RegularExpressionValidator 
                 ControlToValidate="TextBox1"
                 ValidationExpression="^[A-Za-z]\w*"
                 ErrorMessage="Input must start with a letter"
                 runat="server"/>

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

You can use: [A-Za-z]\w* to ensure the first character is a letter and any remaining characters are alphanumeric (optional by using the *)

<asp:RegularExpressionValidator ID="rev" runat="server"
    ControlToValidate="txtBox"
    ErrorMessage="First character must be a letter!"
    ValidationExpression="[A-Za-z]\w*" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtBox" 
    ErrorMessage="Value can't be empty" />

The RequiredFieldValidator is used in conjunction with the RegularExpressionValidator to prevent blank entries. If that textbox is optional, and only needs to be validated when something is entered, then you don't have to use the RequiredFieldValidator.

Upvotes: 1

Related Questions