0

I am not very confortable with regex. I would like the password to have a minimum of 6 characters, including 2 special characters

I tried a first regex but it just returns false each time...

console.log(/^[a-zA-Z0-9!$#%]+$/.test(this.form.password));

I can test the number of characters another way but I would like to include the two special characters through the regex.

Thanks a lot in advance for your help

shrys
  • 5,860
  • 2
  • 21
  • 36
Maxiss
  • 986
  • 1
  • 16
  • 35
  • https://stackoverflow.com/questions/18812317/javascript-regex-for-special-characters/18812336 – The Alpha Jul 10 '19 at 08:52
  • 1
    *"I am not very confortable with regex"* try another approach, then. A loop can do the job – Cid Jul 10 '19 at 08:53

1 Answers1

0

First lookahead for 6 characters, to ensure that enough exist in the input. Then, repeat twice: 0 or more normal characters, followed by a special character, to ensure that there are at least 2 special characters in the input. Then match 0 or more [special or normal] characters.

/^(?=.{6})(?:[a-z\d]*[!$#%]){2}[a-z\d!$#%]*$/i

https://regex101.com/r/ZyFZPm/2

  • ^ - Start of string
  • (?=.{6}) - At least 6 characters
  • (?:[a-z\d]*[!$#%]){2} - Repeat twice:
    • [a-z\d]* - 0+ alphanumeric characters
    • [!$#%] - 1 special character
  • [a-z\d!$#%]* - Match both special and alphanumeric characters up to the end of the string
  • $ - End of string
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320