Regular expressions for password based on a policy

I'm trying to validate the password using regular expressions. The password must follow the following policies:

  • minimum 8 characters
  • maximum 15
  • at least one capital letter
  • at least one minute letter
  • at least one digit
  • No whitespace
  • at least 1 special character

I am using this expression which if it works, but the problem is that it supports me spaces in White:

regexp_password = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}/;
 5
Author: Edgar Conrado, 2016-02-16

6 answers

Try the following regular expression:

var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])([A-Za-z\d$@$!%*?&]|[^ ]){8,15}$/;

regex

 5
Author: Paul Vargas, 2016-02-17 00:42:46

The problem is that this part of the RegExp

[A-Za-z\d$@$!%*?&]{8,15}

Is satisfied with 8 characters of the set. That is, after the eighth character, your regexp allows anything.

What needs to be done is bounded at the end, so that it only accepts strings in which, after the 8 to 15 characters of the allowed character set, the string ends.

TL; DR: you have to add $ at the end.

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}$/

                                                                    acá ^
 3
Author: angus, 2020-06-11 10:54:57

After several attempts I could not achieve it, since as they comment, this method is not very safe. So what I did is a validation before to detect if it has any whitespace

if(/\s/.test($scope.Password)){
    $scope.isValidPassword = false;
    return;
}
 2
Author: Edgar Conrado, 2016-02-16 22:54:24

You would have to deny the whitespace with [^'\s] so the full expression would look like this:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}[^'\s]/

Try it here

 1
Author: Eduardo Munizaga, 2016-02-16 21:40:24

Can validate your regex, and indeed some whitespace cases are valid.

I consider you could remove them before your input, and then validate with your regex.

You can use .replace(/ /g,'') to remove whitespace

Here a small jsfiddle

 1
Author: jasilva, 2016-02-16 22:27:05

I think this part:

([A-Za-z\d$@$!%*?&]|[^ ]) 

Should look like this:

(^[A-Za-z\d$@$!%*?&]+$)

And this way it evaluates in the whole expression from the beginning to the end and there is no need to deny the whitespace, since quw would only accept the characters you are telling it.

 0
Author: Cristian H Calderon, 2018-08-17 19:24:08