JavaScript crude password requirement checker
Wed, 30 September 2020
password-requirements.js
/** * Validate whether a password is at least {minLength} long and matches at * least {minCriteria} of the requirements. * Checks whether the password containers at least 1 of the following: * - Lower case * - Upper case * - Number * - Special character * @param {String} val * @param {number} minLength * @param {number} minCriteria * @returns {boolean} */ let passwordMatchesRequirements = function(val, minLength, minCriteria) { if (val.length < minLength) { return false; } let lower = 'abcdefghijklmnopqrstuvwxyz'; let upper = lower.toUpperCase(); let lowerSplit = lower.split(''); let upperSplit = upper.split(''); let numbers = '0123456789'; let numbersSplit = numbers.split(''); let hasUpper = false; let hasLower = false; let hasNumbers = false; let hasSpecial = false; let valPieces = val.split(''); let c = 0; for (let i=0;i<valPieces.length;i++) { if (hasUpper === false && upperSplit.indexOf(valPieces[i]) !== -1) { hasUpper = true; c++; continue; } if (hasLower === false && lowerSplit.indexOf(valPieces[i]) !== -1) { hasLower = true; c++; continue; } if (hasNumbers === false && numbersSplit.indexOf(valPieces[i]) !== -1) { hasNumbers = true; c++; continue; } if (hasSpecial === false && (upperSplit.indexOf(valPieces[i]) === -1 && lowerSplit.indexOf(valPieces[i]) === -1) && numbersSplit.indexOf(valPieces[i]) === -1) { hasSpecial = true; c++; } } return c >= minCriteria; };