我正在嘗試驗證密碼以查看是否符合以下條件:
- 必須至少有一個大寫字符
- 必須至少有一個小寫字符
- 必須至少有一個數字字符 如果不滿足某個條件,該函式必須逐字逐句地拋出一個錯誤,該錯誤已在條件中指定。
我嘗試使用多個 if 陳述句,因為這樣你可以隔離條件并拋出確切的錯誤,但我試圖找到一種使用物件和回圈的方法。此外,按照 TDD 方法執行此操作,并將 Jasmine 作為我的測驗框架。我所有的測驗都需要一條錯誤訊息,我無法回傳相應的錯誤訊息。
到目前為止,這是我的代碼:
const regexObj = {
lowercaseRegex: {
regex: /[a-z]/,
errorMsg: "password should have at least one lowercase letter",
},
uppercaseRegex: {
regex: /[A-Z]/,
errorMsg: "password should have at least one uppercase letter",
},
oneDigitRegex: {
regex: /[0-9]/,
errorMsg: "password should have at least one digit",
},
specialCharsRegex: {
regex: /[^A-Za-z0-9]/,
errorMsg: "password should have at least one special character",
},
whitespaceRegex: {
regex: /\s/,
errorMsg: "password should have at least one whitespace character",
},
};
function checkPassword(password){
let errorMsgs = [];
for(let x = 0; x < password.length; x ) {
for(let prop in regexObj){
if(!regexObj[prop].regex.test(password[x])){
errorMsgs.push(regexObj[prop].errorMsg);
}
}
}
return (errorMsgs || true);
}
uj5u.com熱心網友回復:
您似乎正在針對密碼的每個字符測驗各種正則運算式。相反,您應該針對整個密碼測驗每個正則運算式。為什么?例如,如果您需要一個小寫字母,您不應該關心該字符在密碼中的位置。只要可以在密碼中的任何位置找到它就可以了。
此外,就目前而言,空白字符將被視為特殊字符,因為它不是字母數字。因此,特殊字符的正則運算式也不應該搜索空白字符。
最后,您的 return 陳述句將永遠不會true像當前撰寫的那樣回傳,因為errorMsgs它將始終評估為true.
const regexObj = {
lowercaseRegex: {
regex: /[a-z]/,
errorMsg: "password should have at least one lowercase letter",
},
uppercaseRegex: {
regex: /[A-Z]/,
errorMsg: "password should have at least one uppercase letter",
},
oneDigitRegex: {
regex: /[0-9]/,
errorMsg: "password should have at least one digit",
},
specialCharsRegex: {
regex: /[^A-Za-z0-9\s]/,
errorMsg: "password should have at least one special character",
},
whitespaceRegex: {
regex: /\s/,
errorMsg: "password should have at least one whitespace character",
},
};
function checkPassword(password) {
let errorMsgs = [];
for (let prop in regexObj) {
if(!regexObj[prop].regex.test(password)) {
errorMsgs.push(regexObj[prop].errorMsg);
}
}
return errorMsgs.length ? errorMsgs : true;
}
console.log(checkPassword('ab C'));
更新
如果你想拋出一個例外而不是回傳一個錯誤陣列,那么:
function checkPassword(password) {
const regexObj = {
lowercaseRegex: {
regex: /[a-z]/,
errorMsg: "password should have at least one lowercase letter",
},
uppercaseRegex: {
regex: /[A-Z]/,
errorMsg: "password should have at least one uppercase letter",
},
oneDigitRegex: {
regex: /[0-9]/,
errorMsg: "password should have at least one digit",
},
specialCharsRegex: {
regex: /[^A-Za-z0-9\s]/,
errorMsg: "password should have at least one special character",
},
whitespaceRegex: {
regex: /\s/,
errorMsg: "password should have at least one whitespace character",
},
};
for (let prop in regexObj) {
if(!regexObj[prop].regex.test(password)) {
throw regexObj[prop].errorMsg;
}
}
return true;
}
console.log(checkPassword('ab C'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532654.html
標籤:javascript验证javascript 对象tdd
下一篇:CAS操作的記憶體屏障使用情況
