Happy .NET
Happy .NET

Reputation: 521

Detect that textbox has one number and one upper letter

Hi I need to use regular expressions in C# to validate a TextBox.

Regular expressions should validate that the textbox has one number and one uppercase letter

My code is:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
    ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator" 
    ValidationExpression="[A-Z a-z 0-9]*[0-1]+[A-z]+"></asp:RegularExpressionValidator>

but it's not allowing

nameA123

Where is my error?

Upvotes: 3

Views: 1475

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

The below regex would validates for atleast one uppercase alpha and one number and it won't care about any character including special characters.

^(?=.*[A-Z])(?=.*[0-9]).*$

DEMO

Upvotes: 0

zx81
zx81

Reputation: 41838

Use this regex:

^(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$

In the regex demo, you can add strings to see if they match.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • The lookahead (?=.*[A-Z]) asserts that at it is possible to match some chars then an uppercase letter
  • The lookahead (?=.*[0-9]) asserts that at it is possible to match some chars then a digit
  • [a-zA-Z0-9]+ matches letters and digits
  • The $ anchor asserts that we are at the end of the string

Reference

Upvotes: 3

Related Questions