Btwonu

passwordValidator

Jun 17th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. function passwordValidator(pass) {
  4.  
  5.   //Check characters
  6.   let passwordHasValidLength = validatePasswordLength(pass, 6, 10)
  7.  
  8.   //Check for symbols
  9.   //Check if 2 digits are used
  10.   let passwordAsciiCharacters = returnAsciiCodesArray(pass);
  11.  
  12.   //Allowed ascii ranges
  13.   // let asciiDigitRange = 48-57;  
  14.   // let asciiUpperRange = 65-90;
  15.   // let asciiLowerRange = 97-122;
  16.   let passWithOnlyAllowedSymbols = filter(passwordAsciiCharacters, (ele) => {
  17.     return (ele >= 48 && ele <= 57) || (ele >= 65 && ele <= 90) || (ele >= 97 && ele <= 122);
  18.   });
  19.  
  20.   //Compare filtered array with old password array
  21.   let passwordHasValidSymbols = compareArrayElements(passwordAsciiCharacters, passWithOnlyAllowedSymbols);
  22.  
  23.   //Filter just the digits out of the password and count them
  24.   let passDigitsArray = filter(passwordAsciiCharacters, (ele) => {
  25.     return (ele >= 48 && ele <= 57);
  26.   });
  27.   let allDigitsInPassword = passDigitsArray.length;
  28.  
  29.   //Conditions
  30.   if (!passwordHasValidLength) {
  31.     console.log('Password must be between 6 and 10 characters');
  32.   }
  33.  
  34.   if (!passwordHasValidSymbols) {
  35.     console.log('Password must consist only of letters and digits');
  36.   }
  37.  
  38.   if (allDigitsInPassword < 2) {
  39.     console.log('Password must have at least 2 digits');
  40.   }
  41.  
  42.   if (passwordHasValidLength && passwordHasValidSymbols && allDigitsInPassword >= 2) {
  43.     console.log('Password is valid');
  44.   }
  45.  
  46.   //Declarations
  47.   function returnAsciiCodesArray(string) {
  48.     let codesArray = [];
  49.  
  50.     for (let i = 0; i < string.length; i++) {
  51.       let ascii = string.charCodeAt(i)
  52.       codesArray.push(ascii);
  53.     }
  54.     return codesArray;
  55.   }
  56.  
  57.   function validatePasswordLength(pass, startReq, endReq) {
  58.     return pass.length >= startReq && pass.length <= endReq;
  59.   }
  60.  
  61.   function filter(arr, callback) {
  62.     let newArr = [];
  63.  
  64.     for (let element of arr)  {
  65.       if (callback(element)) {
  66.         newArr.push(element);
  67.       }
  68.     }
  69.     return newArr;
  70.   }
  71.  
  72.   function compareArrayElements(arrOne, arrTwo) {
  73.     let bool = null;
  74.  
  75.     for (let i = 0, j = arrOne.length; i < j; i++) {
  76.       let stringOne = arrOne[i];
  77.       let stringTwo = arrTwo[i];
  78.       bool = stringOne === stringTwo ? true : false;
  79.     }
  80.     return bool;
  81.   }
  82. }
  83.  
  84. let result = passwordValidator('Pa$s$s');
  85. console.log(result);
Add Comment
Please, Sign In to add comment