In my web application, I have a text box.
The user should enter a value of which the first character is a letter, n开发者_如何学运维ot a digit, and the remaining characters can be alphanumeric.
How can I write regular expression to do this?
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.
<asp:TextBox id="TextBox1" runat="server"/>
<asp:RegularExpressionValidator
ControlToValidate="TextBox1"
ValidationExpression="^[A-Za-z]\w*"
ErrorMessage="Input must start with a letter"
runat="server"/>
精彩评论