Validating a password using JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a password string as the first and the only argument.

Then function should return true, if the password string −

  • is at least 6 characters long and at most 20 characters long

  • contains at least one digit.

  • contains at least one lowercase English character.

  • contains at least one uppercase English character.

  • contains at least one special character. The special characters are: !@#$%^&*()-+

Example

The code for this will be −

 Live Demo

const valid = '12Aatab@';
const invalid = '1234ASD+';
const validatePassword = (str = '') => {
   const { length: l } = str;
   const strArr = str.split('');
   if(l < 6 || l > 20){
      return false;
   };
   const specialCharacters = '!@#$%^&*()-+';
   const alphabets = 'abcdefghijklmnopqrstuvwxyz';
   const numbers = '0123456789';
   const checkWith = (char, set) => set.includes(char);
   const containsSpecialCharacter = strArr.some(char => checkWith(char, specialCharacters));
   const containsLowercase = strArr.some(char => checkWith(char, alphabets));
   const containsUppercase = strArr.some(char => checkWith(char, alphabets.toUpperCase()));
   const containsNumber = strArr.some(char => checkWith(char, numbers));
   return containsSpecialCharacter && containsLowercase && containsUppercase && containsNumber;
};
console.log(validatePassword(valid));
console.log(validatePassword(invalid));

Output

And the output in the console will be −

true
false
raja
Published on 24-Feb-2021 10:25:17
Advertisements