Home > Blockchain >  HTML5 Pattern (regex) for symbols not working
HTML5 Pattern (regex) for symbols not working

Time:09-12

I cannot believe it came down to this, but honestly I cannot figure out why browsers do not want to use the symbol pattern I define for password validation.

Take the following example:

<input type="password" id="pwd" name="pwd" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">

Can be reproduced there (taken from here): https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_pattern3

It works accordingly. The moment I try to add symbols requirement as well:

  <input type="password" id="pwd" name="pwd" pattern="(?=.*\d)(?=.*[a-z])(?=.*[~!@#$%^&* -_/.,{}[\]();:|?<>=]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">

Game over. It won't require a symbol as well, you can submit without symbols and even without numbers.

I have tried all sorts of escaping, it just won't work further than the sign.

My desired allowance of symbols would be (note, intentionally un-escaped for reading):

~!@#$%^&* -_/.,\{}[]();:|?<>="'`

I believe the above should cover all symbols to allow users to use strong passwords (usually from password generators).

So the final result for validation would be:

  • At least 8 characters
  • At least one uppercase
  • At least one lowercase
  • At least one symbol (special character)

Can someone shed some light on this please? Is there a specific set of symbols allowed in HTML inputs or I am just not escaping them right?

Many thanks

CodePudding user response:

I have tested each character individually until I have found the culprit. It seems a bit different than escaping JS based pattern/regex.

Essentially you need to escape the following characters only:

- \ [ ]

The character " does not work.

The final working pattern is:

pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&* \-_/.,\\{}\[\]();:|?<>='`]).{8,}"

With the above you can allow the following symbols:

~ ! @ # $ % ^ & *   - / . , \ { } [ ] ( ) ; : | ? < > = ' `

CodePudding user response:

you should put your regex between //i like this:

<input type="password" id="pwd" name="pwd" pattern="/~!@#$%^&* -_/.,\{}[]();:|?<>="'`/i" ....../>

CodePudding user response:

Try this please.

<input type="text" pattern="^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$">

  • Related