const createPassword = (min, max) => { // 可以生成隨機密碼的相關數組 const num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const english = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; const ENGLISH = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; const config = num.concat(english).concat(ENGLISH); // 隨機從數組中抽出一個數值 const getOne = arr => arr[Math.floor(Math.random() * arr.length)]; // 先放入一個必須存在的 const arr = []; arr.push(getOne(num)); arr.push(getOne(english)); arr.push(getOne(ENGLISH)); // 獲取需要生成的長度 const len = min + Math.floor(Math.random() * (max - min + 1)); for (let i = 4; i < len; i++) { // 從數組里面抽出一個 arr.push(config[Math.floor(Math.random() * config.length)]); } // 亂序 const newArr = []; for (let j = 0; j < len; j++) { newArr.push(arr.splice(Math.random() * arr.length, 1)[0]); } return newArr.join(''); }; // 生成隨機密碼 const randomPassword = createPassword(8, 20);
2.8~20 位同時包含數字和大小寫字母,符號僅限 !@#$%^*()正則校驗
const checkPassword = password => { // 8~20 位同時包含數字和大小寫字母,符號僅限 !@#$%^*() const pattern = /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/; if (pattern.test(password) || /(?![0-9A-Z!@#$%^*()]+$)(?![0-9a-z!@#$%^*()]+$)(?![a-zA-Z!@#$%^*()]+$)[0-9A-Za-z!@#$%^*()]{8,20}$/.test(password)) { return true; } return false; };