Further modifying regex for password

How can you change this regular expression for letters and numbers only?

I thought, believing that it should have at least 2 uppercase letters, lowercase letters and numbers, that this limits the expression to only these types of characters. But this allows unwanted characters like tildes, etc.

/^[\s]*((?=([^\s]*\d){2,})(?=([^\s]*[a-z]){2,})(?=([^\s]*[A-Z]){2,})[^\s]{8,16})[\s]*$/
0
source share
3 answers

Here is a way to do this using a few needles. violin

alert( verify('AbcdeFghij123') );
alert( verify('Abcdeghij123') ); // Only 1 capital
alert( verify('AbcdeFghij') ); // No numbers
alert( verify('ABCDEF123') ); // No lowercase
alert( verify('Abc~~ghij123') ); // Tilde
alert( verify('') ); // Blank

function verify(pass) {
    return /^[A-Za-z0-9]+$/.test(pass)
        && /[A-Z][^A-Z]*[A-Z]/.test(pass)
        && /[a-z][^a-z]*[a-z]/.test(pass)
        && /[0-9][^0-9]*[0-9]/.test(pass);
}

If you want to limit the size between X and Y, replace /^[A-Za-z0-9]+$/with /^[A-Za-z0-9]{X,Y}$/. Pretty simple, huh ??

+1
source

, . , .

, , , , , :

/[A-Za-z0-9]{8,16}/

( , , ), :

/[A-Z].*[A-Z]/
/[0-9].*[0-9]/
/[a-z].*[a-z]/

, , , .

, .

FWIW, , - http://txt2re.com

+2

Here is a proven function that will check the password with your requirements:

/*  Validate a password string that has:
    * From 8 to 16 letters and digits.
    * Optional leading and trailing whitespace.
    * At least 2 uppercase letters.
    * At least 2 lowercase letters.
    * At least 2 decimal digits.
    Here is the regex in (PHP) free-spacing mode with comments:
    $re = '/# Validate password has 2 upper, 2 lower and 2 digits.
        ^                        # Anchor to start of string.
        (?=(?:[^A-Z]*[A-Z]){2})  # Assert 2 uppercase letters.
        (?=(?:[^a-z]*[a-z]){2})  # Assert 2 lowercase letters.
        (?=(?:[^0-9]*[0-9]){2})  # Assert 2 decimal digits.
        \s*                      # Allow leading whitespace.
        ([A-Za-z0-9]{8,16})      # $1: Password 8-16 of [A-Za-z0-9]
        \s*                      # Allow trailing whitespace.
        $                        # Anchor to end of string.
        /x';
    If valid password, return password trimmed of leading and trailing whitespace.
    If invalid password, return empty string.
*/
function validatePassword(text)  {
    var re = /^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^0-9]*[0-9]){2})\s*([A-Za-z0-9]{8,16})\s*$/;
    var m = text.match(re);
    if (m) return m[1];     // If valid, return trimmed password
    return '';              // If not valid, return empty string
}
+1
source

Source: https://habr.com/ru/post/1540233/


All Articles