Last active
August 29, 2015 13:59
-
-
Save ducdhm/10623431 to your computer and use it in GitHub Desktop.
Generate password regexp for validating purpose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate password regex | |
* @method generatePasswordRegex | |
* @param {Number} min Minimum length of password | |
* @param {Number} max Maximum length of password | |
* @param {String} specialCharacter List of special characters | |
* @param {Number} specialLength Number of required special character in password | |
* @param {Number} uppercaseLength Number of required uppercase character in password | |
* @param {Number} numberLength Number of digit character in password * | |
*/ | |
function generatePasswordRegex(options) { | |
var regexString = '(?=(?:.*[a-z]){1})'; | |
if (options.uppercaseLength > 0) { | |
regexString += '(?=(?:.*[A-Z]){' + options.uppercaseLength + '})'; | |
} | |
if (options.numberLength > 0) { | |
regexString += '(?=(?:.*\\d){' + options.numberLength + '})'; | |
} | |
if (options.specialLength > 0) { | |
regexString += '(?=(?:.*[' + options.specialCharacter + ']){' + options.numberLength + '})'; | |
} | |
regexString += '.{' + options.min + ',' + options.max + '}'; | |
return new RegExp('^' + regexString + '$'); | |
} | |
var regex = generatePasswordRegex({ | |
min: 8, | |
max: 32, | |
specialCharacter: '!@#$%^&*-', | |
specialLength: 1, | |
uppercaseLength: 1, | |
numberLength: 1 | |
}); | |
console.log('Passw0rd@'); // true | |
console.log('@Passw0rd'); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment