Regular expression for accepting alphanumeric characters (6-10 chars) .NET, C#

Madhu picture Madhu · Feb 3, 2010 · Viewed 23.4k times · Source

I am building a user registration form using C# with .NET. I have a requirement to validate user entered password fields. Validation requirement is as below.

  1. It should be alphanumeric (a-z , A-Z , 0-9)
  2. It should accept 6-10 characters (minimum 6 characters, maximum 10 characters)
  3. With at least 1 alphabet and number (example: stack1over)

I am using a regular expression as below.

^([a-zA-Z0-9]{6,10})$

It satisfies my first 2 conditions. It fails when I enter only characters or numbers.

Answer

paxdiablo picture paxdiablo · Feb 3, 2010

Pass it through multiple regexes if you can. It'll be a lot cleaner than those look-ahead monstrosities :-)

^[a-zA-Z0-9]{6,10}$
[a-zA-Z]
[0-9]

Though some might consider it clever, it's not necessary to do everything with a single regex (or even with any regex, sometimes - just witness the people who want a regex to detect numbers between 75 and 4093).

Would you rather see some nice clean code like:

if not checkRegex(str,"^[0-9]+$")
    return false
val = string_to_int(str);
return (val >= 75) and (val <= 4093)

or something like:

return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$")

I know which one I'd prefer to maintain :-)