Reputation: 81
I am trying to build a regex that matches for the following
my special characters from my backend to support js special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;,'\[\]]"
and a minimum of a length of at least 8 or longer.
my password javascript client-side is the following, but however, how can I build a regex with the following data?
if (password === '') {
addErrorTo('password', data['message']['password1']);
} else if(password){
addErrorTo('password', data['message']['password1']);
}else {
removeErrorFrom('password');
}
Upvotes: 1
Views: 200
Reputation: 1804
You can use multiple REGEXes to check for each requirement.
let containsAtLeastSixChars = /(\w[^\w]*){6}/.test(password);
let containsAtLeastTwoDigits = /(\d[^\d]*){2}/.test(password);
let containsAtLeastOnePunct = new RegExp(special_characters).test(password);
let isAtLeast8Digits = password.length >= 8;
Then if any of these booleans are false, you can inform the user. A well designed site will show which one is wrong, and display what the user needs to fix.
Upvotes: 2
Reputation: 1
^(?=.*[0-9]).{2}(?=.*[a-zA-Z]).{6}(?=.*[!@#$%^&*(),.?":{}|<>]).{1}$
6Letters, 2digits, and 1 special character.
Upvotes: 0
Reputation: 591
First check if password.length >= 6
Then I would do it like this:
letterCount
, numCount
, puncCount
letterCount
(letterCount++
), each time you encounter a number increase numCount
and so on.This is a good approach because you can tell the user what went wrong. For example, if they only entered 1 number, you can see that from the numCount
and tell them specifically that they need at least 2 numbers. You can't do that with just one Regex.
EDIT: Heres the code:
for (let i = 0; i < password.length; i++) {
const currentChar = password[i];
if (checkIfLetter(currentChar)) {
letterCount++;
}
if (checkIfNumber(currentChar)) {
numCount++;
}
if (checkIfPunc(currentChar)) {
puncCount++;
}
}
Then check if the numCount > 2
and so on. I would write the actual regexs but I don't know them myself. It should be pretty easy, just return true
if the provided char is a letter for the first function, a number for the second one and so on.
Upvotes: 2