javascript – Regular expression for a password from 6 characters using numbers, special. characters, Latin, the presence of lowercase and uppercase characters


You need to set up a regular expression for the "Strong 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;


You need to use a positive forward look . It will provide all the conditions you have listed.

This is what the whole expression looks like:


Here's an example on regex101 . You can try writing your passwords and test the regular expression against your requirements.


  • (?=.*[0-9]) – the string contains at least one number;
  • (?=.*[!@#$%^&*]) – the string contains at least one special character;
  • (?=.*[az]) – the string contains at least one lowercase Latin letter;
  • (?=.*[AZ]) – the string contains at least one uppercase Latin letter;
  • [0-9a-zA-Z!@#$%^&*]{6,} – the string consists of at least 6 above-mentioned characters.

Based on the answer to the question:
" Javascript regular expression password validation having special characters "


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 the required character set must be specified instead of %s .

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

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

To make it easier to read such a regular expression in the code, and to make it 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');


// Набор правил
// Имена ключей в этом объекте могут быть любыми
// Они для лучшего понимания частей итогового регулярного выражения
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 a check for the larger of the two arguments min and max and the like. It is only intended to show you an approach that can make it easier to debug such complex regular expressions.

Scroll to Top