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" ) );
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,}$/
Source:stackexchange.com