0

I wanted to make a function in JS that validates a password. The password must have at least 8 and at most 32 characters, at least one uppercase letter, one lowercase letter and a number. Also it should return 1 when it fulfills all requirements and 0 when it doesn't.
My program returns a boolean value, but even when it's true, it keeps returning 0. What should I do?

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

console.log(validatePassword.test("Password10"))

if (validatePassword == true) {
    console.log("1")
}
  
else {
    console.log("0")
}
Débora
  • 13
  • 1

3 Answers3

0

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

function validate(password){
  return pattern.test(password) ? 1 : 0;
}

console.log(validate("Password10"))
Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14
0

You are vaildating the existence of your compiled regex variable.

This works:

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

function isPasswordValid(p) {
  return passRegex.test(p) ? 1 : 0;
}

console.log(isPasswordValid("Password10"));
console.log(isPasswordValid("Pass0"));
Philipp Molitor
  • 387
  • 4
  • 14
0

You forgot to save the result of your test method to variable, and you put it in if. That is why even if it was true it never went inside the if statement. Save it to variable first and then compare in if like this

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

let result = validatePassword.test("Password10")
console.log(result)

if (result == true) {
    console.log("1")
} else {
    console.log("0")
}
Evgeny Klimenchenko
  • 1,184
  • 1
  • 6
  • 15