Home > front end >  how i can validate password with node.js
how i can validate password with node.js

Time:11-06

I test my front-end(html & css) code if it's have error or bug or something but I got a bug

My problem need back-end (node.js) not front-end(html & css).

My problem is password validate. My password validate is need typical any password validate likes

Must password at least one number and one uppercase and lowercase letter, and at least 8 or more characters.

I tried twice to fix this problem, but all failed.

My first try was addidding this code

  letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  cap_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    if(newpassword.length <= 8 || 
       newpassword.search(numbers) < 1 || 
       newpassword.search(cap_letters) < 1 || 
       newpassword.search(letters) < 1) {
      res.send("error")
    } 

My second try was this code

  letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  cap_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    if(newpassword.length <= 8 || 
      !newpassword.match(numbers) || 
      !newpassword.match(cap_letters) || 
      !newpassword.match(letters)){
      res.send("error")
    } 

But neither worked as expected.

CodePudding user response:

The match function receives a regex. Use:

var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
if(!password.match(passw)){res.send("bad password")}
  • Related