0

i try to validate PW with this code

$.validator.addMethod("pwcheck", function(value) {
return /[^\W\s]/gi.test(value) // match any wordCharacter
    && /[a-z]/.test(value) // has a lowercase letter
    && /[A-Z]/.test(value) // has a uppercase letter
    && /\d/.test(value) // has a digit      
    && /(?=.*?\W)/.test(value) // has a specialChar
});

Unfortunately it doesn´t work if my PW has a underscore as sinlge special chararcter, e.g. 1_Testing

What can be done? Thanks in advance

Sparky
  • 98,165
  • 25
  • 199
  • 285
summsel
  • 78
  • 2
  • 9
  • Replace `/(?=.*?\W)/` with `/(?=.*?[\W_])/` – Wiktor Stribiżew Jun 17 '20 at 14:41
  • 1
    This exactly answers your question. [Validation for passwords with special characters](https://stackoverflow.com/questions/62400363/validation-for-passwords-with-special-characters) –  Jun 17 '20 at 16:02
  • @Mandy8055 The questions are asked in a similar way, but the requirements and problem are different. – Wiktor Stribiżew Jun 17 '20 at 17:02
  • @Mandy8055 I might have misunderstood the question. Let's hear from OP, if summsel agrees with the duplicate, then I have misinterpreted the current problem. – Wiktor Stribiżew Jun 17 '20 at 17:05
  • No @WiktorStribiżew; I don't have any problem with the answer that you have. It's impeccable as always but I thought that it's a duplicate so thought to get your view on it. –  Jun 17 '20 at 17:08
  • @Mandy8055 your similar question is good, too. Wiktors answer is straight to the point. Thx to both of you! – summsel Jun 17 '20 at 20:08

1 Answers1

1

There are two issues that need a fix:

  • \W also matches whitespaces, [\W\s] is equalt to \W. Thus, /[^\W\s]/ should be just /\w/
  • \W does not match underscores. When you require a special character and an underscore is treated as a special character, you need to use a [\W_] character class

Note also, that regexps used with RegExp#test should never be used with a g flag, it might lead to issues like this (not the case here, but as a best practice). Also, \w matches any lower- and uppercase ASCII letters, so not need to use a case insensitive i modifier here.

So, you may use

return /\w/.test(value)        // match any wordCharacter
    && /[a-z]/.test(value)     // has a lowercase letter
    && /[A-Z]/.test(value)     // has a uppercase letter
    && /\d/.test(value)        // has a digit      
    && /^[^\W_]*[\W_]/.test(value) // has a specialChar
});

The ^[^\W_]*[\W_] pattern means

  • ^ - match start of string
  • [^\W_]* - 0 or more chars other than non-word chars or _ (i.e. 0 or more letters or digits)
  • [\W_] - a non-word char or a _ char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563