Regular Expression for Secure Password

Asked

Viewed 87 times

0

I need some help to be able to include in the regular expression I’m using to not allow spaces.

The password must meet the following requirements:

  • Have at least 1 number;
  • At least 1 capital letter;
  • Has at least 1 lower case letter;
  • Has at least 1 special character;
  • Not allow space

I’m using the following expression:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_@#$%]).{8,}

1 answer

1

Your expression looks good, but replace the =. for =.?*.
In addition, special characters are missing in the last group, and it is not in the question, but it is also limiting to a minimum of 8 characters (last group of the Expression).

It could be something like:

$("input").keypress(function(){
    var input = $(this).val();
    var regex = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$");
    
    if(regex.test(input)) {
        $("#mensagem").hide();
    }else {
        $("#mensagem").show();
    }
});
label {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />
<label id="mensagem">Inválido</label>

  • The only problem is that you keep accepting space

  • @Andrémachadodevargas Accepts space because in the end it has .{8,} and the point corresponds to any character (including spaces). If you want to limit what you can have, you have to be more specific, for example: ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_@#$%])[-\w@#$%]{8,}$. I traded the point for [-\w@#$%] (the \w is a shortcut to letters, numbers and _), so you can only have the characters that are between the keys. See here the regex working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.