miroLLL

Password Validator

Oct 11th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function passwordValidator(password) {
  2.  
  3.     let lengthValidation = hasRequiredLength(password);
  4.     let conditionValidation = hasValidCharacters(password);
  5.     let digitContainsValidation = hasAtleastTwoDigits(password);
  6.  
  7.     if (lengthValidation && conditionValidation && digitContainsValidation) {
  8.         console.log('Password is valid')
  9.     }
  10.  
  11.     function hasRequiredLength(password) {
  12.  
  13.         let isInRange = password.length >= 6 && password.length <= 10;
  14.  
  15.         if (!isInRange) {
  16.             console.log('Password must be between 6 and 10 characters');
  17.         }
  18.  
  19.         return isInRange;
  20.     }
  21.  
  22.     function hasValidCharacters(password) {
  23.         let characters = password.split('');
  24.  
  25.         let isValid = true;
  26.  
  27.         for (let letter of characters) {
  28.  
  29.             let assciiValue = letter.charCodeAt();
  30.  
  31.             if (!isDigit(assciiValue) && !isCapitalLetter(assciiValue) && !isLowerLetter(assciiValue)) {
  32.                 isValid = false;
  33.                 break;
  34.             }
  35.         }
  36.  
  37.         if (!isValid) {
  38.             console.log('Password must consist only of letters and digits');
  39.         }
  40.  
  41.         return isValid;
  42.  
  43.         function isDigit(char) {
  44.             return char >= 48 && char <= 57;
  45.         }
  46.  
  47.         function isCapitalLetter(char) {
  48.             return char >= 65 && char <= 90;
  49.         }
  50.  
  51.         function isLowerLetter(char) {
  52.             return char >= 97 && char <= 122;
  53.         }
  54.     }
  55.  
  56.     function hasAtleastTwoDigits(password) {
  57.  
  58.         let digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
  59.         let digitCounter = 0;
  60.  
  61.         password.split('').forEach((letter) => {
  62.  
  63.             let value = Number(letter);
  64.  
  65.             if (digits.includes(value)) {
  66.                 digitCounter++;
  67.             }
  68.         })
  69.  
  70.         let hasMinimumDigits = digitCounter >= 2;
  71.  
  72.         if (!hasMinimumDigits) {
  73.             console.log("Password must have at least 2 digits");
  74.         }
  75.  
  76.         return hasMinimumDigits
  77.     }
  78. }
Add Comment
Please, Sign In to add comment