There is a field with a password. It is necessary to validate with the following condition:

The minimum password length is 8 characters.
maximum length of 20 characters
The field must contain lower and upper case Latin letters, at least 4 letters + special characters.
Tried to do the following way - did not work:

(?=.*\d)((?=.*[az])|(?=.*[AZ]){4,}).{8,20} 
  • one
    Do you basically check all this with one regular? And if you later want to further complicate the conditions of validation? Regeksp-monster work. After six months, you will not be able to immediately understand what is happening inside. Why not make a few checks by combining their results with a logical AND? - AntonioK
  • If it will be combined into one line, it does not matter. There are suggestions how to implement this? - Armm
  • So after all the whole jQuery, for example, can be combined into one line. Only the string is long. They do this in production to reduce the size of the code transferred to the client - what's the point when developing? - AntonioK
  • one
    The point, I suspect, is that the teaching lab has formulated that way =) - Sergey Snegirev
  • The meaning is that you need to fulfill the condition) - Armm

2 answers 2

 ^(?=.*\d)(?=.*[az])(?=.*[AZ])(?=(.*[a-zA-Z]){4}).{8,20}$ 

    The easiest way is to do a check for each condition, that is, take a string with a password, and

    • check that it is not less than the minimum length
    • check that it is not more than the maximum length
    • check whether the regular expression "anything where there is at least one special character"
    • check whether the regular expression "anything where there is (любая буква в нижнем регистре И любая буква в верхнем регистре)x4 штуки
    • etc.

    Then you apply a logical AND to all the checks and find out whether all the conditions agreed or not.

    • I’m most interested in just this point: check whether the regular expression "anything where there is (any lower case letter And any upper case letter) x4 pieces. Could you give an example? - Armm
    • And for the convenience of the user, you can not just say "the password does not meet the criteria," but explain what exactly he forgot to include in the string. - Sergey Snegirev
    • ^(?=.*[az])(?=.*[AZ]).{4,}$ - AntonioK
    • This example is not exactly what I need. By the condition of all characters in the password should be from 8 to 20, and 4 of them are letters. - Armm
    • I wrote you a regular list of что угодно, где есть (любая буква в нижнем регистре И любая буква в верхнем регистре)x4 штуки . Above, I proposed to make several hotel checks, this is one of them. What you do not understand? How to combine the results of checks? - AntonioK