3

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>
Bavi Gurunath
  • 73
  • 1
  • 6

1 Answers1

1

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.
Ciabaros
  • 1,984
  • 13
  • 15
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • IMPORTANT: To clarify, the pattern must CAPTURE your entire input, not just match it. This is why you need the .* – Ciabaros Mar 06 '20 at 20:46
  • 1
    @Ciabaros It is not capturing here, it is *consuming*. To capture, you need to use capturing groups, and there are none here. – Wiktor Stribiżew Mar 06 '20 at 20:49
  • My pattern is very simple: `[A-Za-z]{2,30}` no forward slashed and the quantifier is enough, right? It has the `required` attribute and the input field still accepts characters like 1,2,3,@#$%^... I mean they are VALIDATED right, why? It happens in my local environment. I use Dreamweaver and at coding I also test with Brackets. One note: I am working with local server. My HTML contact form is saved as php. Does it have to do with client validation isues? – limakid Apr 24 '23 at 21:49
  • @limakid Please read the `pattern` attribute docs. The regex there does not limit the *user input*, the validation happens *on submit*. You can type anything there if you do not provide an extra coding. – Wiktor Stribiżew Apr 25 '23 at 06:51