Question:
You need to set up a regular expression for "Complex password": from 6 characters using numbers, special. characters, Latin, the presence of lowercase and uppercase characters.
If the entered characters do not match the given expression, then return false;
Answer:
Positive look ahead must be used. It will ensure all the conditions you listed.
This is what the whole expression looks like:
/(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!@#$%^&*]{6,}/g
Here is an example with regex101 . You can try writing your own passwords and see if the regular expression matches your requirements.
Explanation:
-
(?=.*[0-9])
– string contains at least one number; -
(?=.*[!@#$%^&*])
– string contains at least one special character; -
(?=.*[az])
– the string contains at least one Latin letter in lower case; -
(?=.*[AZ])
– string contains at least one uppercase latin letter; -
[0-9a-zA-Z!@#$%^&*]{6,}
– string consists of at least 6 of the above characters.
Based on the answer to the question:
" Javascript regular expression password validation having special characters "
Update
It is important to understand that in order to check the mandatory presence of certain characters in a string, it is enough to use the following pattern: (?=.*[%s])
, where instead of %s
you need to specify the required set of characters.
The pattern must be at the very beginning of the regular expression and be present as many times as you want to use unique string validation rules.
After a segment with repetitions of this pattern, a generalized set of all allowed characters must be used. We need to glue the “pieces” into one common set of allowed characters. Then it will need to apply a character limit corresponding to the selected string length.
To make such a regular expression easier to read in the code and easier to check, in case of a typo, you can use the following function to generate the final expression:
function makePasswordRegExp(patterns, min, max) {
var min = min || ''; // Если минимальное число символов не указано, берём пустую строку
var max = max || ''; // Если максимальное число символов не указано, берём пустую строку
var regex_string = '';
var rules = [];
var range = "{" + min + "," + max + "}"; // Разрешённый диапазон для длины строки
for (rule in patterns) { // Обрабатываем входящий массив из ВСЕХ правил для строки
if (patterns.hasOwnProperty(rule)) {
rules.push(patterns[rule]); // Запоминаем правила
// Формируем последовательность из шаблонов `(?=.*[%s])`
// Она проверит обязательное присутствие всех символов из входящего набора
regex_string += "(?=.*[" + patterns[rule] + "])";
}
}
// Добавляем в хвост набор из ВСЕХ разрешённых символов и разрешённую длину строки
regex_string += "[" + rules.join('') + "]" + range;
// Собираем всё в одно регулярное выражение
return new RegExp(regex_string, 'g');
}
Usage:
// Набор правил
// Имена ключей в этом объекте могут быть любыми
// Они для лучшего понимания частей итогового регулярного выражения
var patterns = {
'numeric': '0-9',
'special': '!@#$%^&*',
'latin_lower': 'a-z',
'latin_upper': 'A-Z'
};
// В вашем случае есть ограничение только по минимальной длине от 6 символов
var min = 6;
// Передаём правила в функцию и смотрим итоговое выражение
console.log(makePasswordRegExp(patterns, min));
// Вывод: /(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[0-9!@#$%^&*a-zA-Z]{6,}/g
Of course, the function can be improved by adding to it a check of the larger of the two arguments min
and max
and the like. It is only intended to show an approach that can make debugging such complex regular expressions easier.