1

I am using pattern in HTML5 validation. I want a regex to check for such username format:

<letters+><digits*> : total length minimum 8
-> starting with letters then optional digits.

examples: w1234567, qweqr123, jsgwiuegn1274124, qwerasdf, awdjwuadhuf, etc.

wrong examples: 12345678, qwe12qwe, 12qweqwe, qweq12, etc.

I tried ([A-z]+[0-9]*){8,}, It's not working as expected.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sushil Kumar Jain
  • 97
  • 1
  • 2
  • 11

1 Answers1

0

Your regex - ([A-z]+[0-9]*){8,} - matches 8 or more sequences of 1 or chars inside [A-z] range (that matches more than just letters, see Why is this regex allowing a caret?) and 0+ digits. Thus, it does not really set the length restriction.

You may use a lookahead based regex:

pattern="(?=[a-zA-Z\d]{8})[A-Za-z]+\d*"

Note that the pattern is anchored by default and will be passed to the regex engine as ^(?:(?=[a-zA-Z\d]{8})[A-Za-z]+\d*)$. To play it safe, you may add them explicitly: pattern="^(?=[a-zA-Z\d]{8})[A-Za-z]+\d*$"

See the regex demo

Details:

  • ^ - matches the start of string (implicit)
  • (?=[a-zA-Z\d]{8}) - a positive lookahead that requires 8 alphanumeric chars from the start of the string
  • [A-Za-z]+ - 1 or more (+) ASCII letters
  • \d* - zero or more (*) digits
  • $ - end of string (implicit)

input:valid {
  color: navy;
}
input:invalid {
  color: red;
}
<form name="form1"> 
 <input pattern="(?=[a-zA-Z\d]{8})[A-Za-z]+\d*" title=""/>
 <input type="Submit"/> 
</form>
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks! **improvement:** I want minimum 8, so {8,} would work - I guess. **doubt:** I thought [A-z] , [a-Z] are equivalent to [a-zA-Z]. can you explain it more? – Sushil Kumar Jain Sep 30 '16 at 11:08
  • Yes, for a minimum of 8, use `{8,}` limiting quantifier without the max argument, but actually, `{8}` will work the same way here since `$` is not used right after `{8}`. To restrict to just 8 chars, use `pattern="(?=[a-zA-Z\d]{8}$)[A-Za-z]+\d*"`. As for `[A-z]`, see [*Why is this regex allowing a caret?*](http://stackoverflow.com/a/29771926/3832970) Only use `[a-zA-Z]` to only match ASCII letters. – Wiktor Stribiżew Sep 30 '16 at 11:11