You need to set up a regular expression for the "Complex Password": from 6 characters using numbers, special. characters, Latin, the presence of lowercase and uppercase characters.
If the characters entered do not match this expression, then return false;

  • one
    What have you tried and what did not work out? Why should it be a regular expression? - Alexey Ten

2 answers 2

You must use a positive view forward . It will provide all the conditions you listed.

This is what the whole expression looks like:

 /(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[az])(?=.*[AZ])[0-9a-zA-Z!@#$%^&*]{6,}/g 

Here is an example on regex101 . You can try to write your passwords and check the operation of the regular expression to meet your requirements.

Explanation:

  • (?=.*[0-9]) - the string contains at least one number;
  • (?=.*[!@#$%^&*]) - the string contains at least one special character;
  • (?=.*[az]) - the string contains at least one Latin lowercase letter;
  • (?=.*[AZ]) - the string contains at least one Latin uppercase letter;
  • [0-9a-zA-Z!@#$%^&*]{6,} - the 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 presence of certain characters in a string, it is enough to use such a pattern: (?=.*[%s]) , where instead of %s you need to specify the required character set.

The pattern must be at the very beginning of the regular expression and be present as many times as the unique rules for checking the string you want to use.

After the segment with repetitions of this pattern, it is necessary to use a generic set of all allowed characters. We need to glue the "pieces" into one common set of allowed characters. Then to it it will be necessary to apply the limit on the number of characters corresponding to the selected length of the string.

To make such a regular expression easier to read and easier to check in the code, in case of a typo, you can use this 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'); } 

Using:

 // Набор правил // Имена ключей в этом объекте могут быть любыми // Они для лучшего понимания частей итогового регулярного выражения var patterns = { 'numeric': '0-9', 'special': '!@#$%^&*', 'latin_lower': 'a-z', 'latin_upper': 'AZ' }; // В вашем случае есть ограничение только по минимальной длине от 6 символов var min = 6; // Передаём правила в функцию и смотрим итоговое выражение console.log(makePasswordRegExp(patterns, min)); // Вывод: /(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[az])(?=.*[AZ])[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 intended only to show an approach that can simplify the debugging of such complex regular expressions.

  • one
    The regular season is very good, but how much experience do you need to immediately understand what it is and where is the error (if you make a typo)?) Can a normal cycle be more effective for this task, what do you think? - pavel
  • one
    @pavel to understand where the error is in a regular expression, it must be divided into parts, as is done in the explanations for it. Even in terms of readability, the loop will require checking the string for compliance with each of the conditions. The same will come to the same. To make the regular expression easier to read, it can be glued together in the code from its key parts into one whole, and the parts can be assigned speaking variable names. - VenZell
  • @pavel, supplemented the answer by answering your question. - VenZell
  • It Aa% - \0 6dfg not count as complex password Aa% - \0 6dfg , you severely restrict the set of possible characters and due to this you lose a bunch of characters like commas, periods, etc. Solving the problem: 1) add the metacharacter of the beginning of the line to the beginning of the regular expression 2) resolve all characters, that is .{6,} , 3) check for the presence of special characters not limited by the set of characters, and such [^\w\s] - ReinRaus
 /^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[^\w\s]).{6,}/ 

It is very similar to the answer @VenZell, but lacks the disadvantage that the set of valid characters is strictly limited.
It is wrong to require a “complex” password from people and at the same time limit the set of valid characters to a small list !@#$%^&* . If you produce such a brute force password, then there is nothing sweeter - 56 letters, 10 numbers and 8 characters, a total of 74 characters. Well, "very difficult."
When requiring people to have a “complex” password, keep in mind that they may then want to enter \0 © ♣ and a bunch of other characters that are easily entered using ALT+3333 as in the case of the letter symbol.