Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML pattern does't work even with correct regular expression

Tags:

html

regex

Regular expression: ((?=.*\d)(?=.*[A-Z]))

Input string: qwer1Q

The input string above pass the validation if you check it in regex101

However, if you include the regex in a html pattern attribute and try to validate the same string again, it shall not pass:

<form>
  <div>
    <input type="text" placeholder="Password" 
      pattern="((?=.*\d)(?=.*[A-Z]))">
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
like image 342
Bavi Gurunath Avatar asked Nov 01 '25 12:11

Bavi Gurunath


1 Answers

You need to make sure the pattern matches (and consumes) the entire string because the HTML5 pattern regex is anchored by default.

<form>
  <div>
    <input type="text" placeholder="Password" 
      pattern="(?=.*\d)(?=.*[A-Z]).*">
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>

The (?=.*\d)(?=.*[A-Z]).* pattern will be turned into ^(?:(?=.*\d)(?=.*[A-Z]).*)$ and it will match:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • (?=.*\d) - a positive lookahead check to make sure there is at least 1 digit
    • (?=.*[A-Z]) - a positive lookahead check to make sure there is at least 1 uppercase letter
    • .* - any 0+ chars, greedily, up to the end of string
  • ) - end of the non-capturing group
  • $ - end of string.
like image 127
Wiktor Stribiżew Avatar answered Nov 03 '25 03:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!