-2

I am using

/^(?=.\d)(?=.[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

But the problem is when I add any special character like !/@/#... etc, this regex doesn't valid.

for example:

"Customer12" is valid. "@Customer12" is not valid

I need a regex where "Customer12" and "@Customer12" would be valid. regex would not be affected by special character (~!@#$%^&*()_+).

How can I create a regex where password must contain at least eight characters, at least one number and both lower and uppercase letters?

2 Answers2

1

Regex is superior in terms of succinctness. But here is a non-regex solution which becomes ever more so readable for the non-regex linguist:

function validatePasswordWithoutRegex(pw) {
    // Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters
    
    
    pw = pw.trim();
    
    // must contain at least eight characters
    if (pw.length < 8) return false;
    
    let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let numeric = "0123456789";
    
    
    // at least one number 
    let okay = false;
    for (var i = 0; i < numeric.length; i++) {
        if ( pw.indexOf( numeric.charAt( i ) ) != -1) {
            okay = true;
            break;
        }
    }
    if ( !okay ) return false;
    
    // and both lower and uppercase letters (upper)
    okay = false;
    for (var i = 0; i < alpha.length; i++) {
        if ( pw.indexOf( alpha.charAt( i ) ) != -1) {
            okay = true;
            break;
        }
    }
    if ( !okay ) return false;
    
    // and both lower and uppercase letters (lower)
    okay = false;
    for (var i = 0; i < alpha.length; i++) {
        if ( pw.indexOf( alpha.charAt( i ).toLowerCase() ) != -1) {
            okay = true;
            break;
        }
    }
    if ( !okay ) return false;
    
    
    return true; // passed requirements

}

console.log( validatePasswordWithoutRegex( "ABC" ) );
    console.log( validatePasswordWithoutRegex( "hello world" ) );
    console.log( validatePasswordWithoutRegex( "he12World" ) );
    console.log( validatePasswordWithoutRegex( "12345678" ) );
    console.log( validatePasswordWithoutRegex( "123a5678" ) );
    console.log( validatePasswordWithoutRegex( "123a56B8" ) );
    console.log( validatePasswordWithoutRegex( "Hello12rld" ) );
GetSet
  • 1,511
  • 2
  • 10
  • 13
0

Regex expression for Atleast eight characters, at least one letter and one number:

/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/

It you want atleast eight characters, at least one letter and one number and one special character then you can use the below expression.

/"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/
Amaarockz
  • 4,348
  • 2
  • 9
  • 27