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.
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.
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 :-)
Use positive lookahead
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,10}$
Look arounds are also called zero-width assertions. They are zero-width just like the start and end of line (
^
,$
). The difference is that lookarounds will actually match characters, but then give up the match and only return the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.
The syntax for look around:
(?=REGEX)
Positive lookahead(?!REGEX)
Negative lookahead(?<=REGEX)
Positive lookbehind(?<!REGEX)
Negative lookbehindIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With