我使用最快的驗證器進行驗證。我希望密碼欄位至少包含一個字符和一個數字。我需要驗證至少一個字符的訊息和驗證一個數字的訊息。這是我的代碼:
const Validator = require("fastest-validator");
const v = new Validator();
const registerSchema = {
email: { type: "email"},
pass: { type: "string",pattern:'/.*[0-9].*/', min: 8, max: 20 },
};
//also I need a pattern to check at least one char is used and its message specific for it.
exports.validateRegister = v.compile(registerSchema);
uj5u.com熱心網友回復:
可以使用自定義驗證器來完成,請參閱內置規則的自定義驗證:
const Validator = require("fastest-validator");
const v = new Validator({
useNewCustomCheckerFunction: true, // using new version
messages: {
// Register our new error message text
atLeastOneLetter: "The pass value must contain at least one letter from a-z and A-Z ranges!",
atLeastOneDigit: "The pass value must contain at least one digit from 0 to 9!"
}
});
const schema = {
email: {type:"email"},
pass: {
type: "string",
custom: (v, errors) => {
if (!/[0-9]/.test(v)) errors.push({ type: "atLeastOneDigit" });
if (!/[a-zA-Z]/.test(v)) errors.push({ type: "atLeastOneLetter" });
return v;
},
min:8,
max:20,
messages: {
stringPattern: "pass value must contain a digit",
stringMin: "Your pass value is too short",
stringMax: "Your pass value is too large",
}
}
}
const check = v.compile(schema);
console.log( check( {email:"[email protected]", pass: "JohnABCD"} ));
console.log( check( {email:"[email protected]", pass: "123456789"} ));
console.log( check( {email:"[email protected]", pass: "12A"} ));
console.log( check( {email:"[email protected]", pass: "12A12A12A12A12A12A12A12A12A12A"} ));
輸出node fv.js(這是我使用上述代碼命名檔案的方式):
# node fv.js
[ { message:
'The pass value must contain at least one digit from 0 to 9!',
field: 'pass',
type: 'atLeastOneDigit' } ]
[ { message:
'The pass value must contain at least one letter from a-z and A-Z ranges!',
field: 'pass',
type: 'atLeastOneLetter' } ]
[ { type: 'stringMin',
message: 'Your pass value is too short',
field: 'pass',
expected: 8,
actual: 3 } ]
[ { type: 'stringMax',
message: 'Your pass value is too large',
field: 'pass',
expected: 20,
actual: 30 } ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355650.html
標籤:javascript 节点.js 正则表达式 表达 验证
