有没有办法使用 Joi 来做到这一点?
例如:
Joi.string()
.required()
.min(8)
.max(16)
.pattern(/(?=(?:.*[a-z]){2,16}).+/)
.pattern(/(?=(?:.*[A-Z]){2,16}).+/)
.pattern(/(?=(?:.*[0-9]){2,16}).+/)
.pattern(/(?=(?:.*[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]){2,16}).+/)
.messages({
'string.base': 'Username must be of type string',
'string.regex': 'Username must contain at least two lower-case letters',
'string.regex2': 'Username must contain at least two upper-case letters',
'string.regex3': 'Username must contain at least two numbers',
'string.regex4': 'Username must contain at least two special characters',
'string.min': 'Username must be at least 8 characters long',
'string.max': 'Username must be no more than 16 characters long',
'string.empty': 'Username is a required field',
}),
})
});
我似乎遇到的唯一问题是获取正则表达式的良好错误消息。消息的密钥应该是什么?我还想查看所有失败的验证,而不仅仅是第一个失败的验证?有更好的方法吗?
const passwordSchema: ObjectSchema = Joi.object().keys({
password: Joi.string()
.min(8)
.max(16)
.pattern(/(?=(?:.*[a-z]){2,16}).+/, 'lowercase')
.pattern(/(?=(?:.*[A-Z]){2,16}).+/, 'uppercase')
.pattern(/(?=(?:.*[0-9]){2,16}).+/, 'number')
.pattern(/(?=(?:.*[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]){2,16}).+/, 'special')
.required()
.error((errors) => {
errors.forEach((err) => {
switch (err.code) {
case 'string.base':
case 'string.empty':
case 'any.required':
default:
err.message = defaultErrorMessage;
break;
case 'string.min':
err.message = minLengthMessage;
break;
case 'string.max':
err.message = maxLengthMessage;
break;
case 'string.pattern.name':
switch (err.local.name) {
case 'lowercase':
err.message = 'must contain at least two lower-case letters';
break;
case 'uppercase':
err.message = 'must contain at least two lower-case letters';
break;
case 'number':
err.message = 'must contain at least two numbers';
break;
case 'special':
err.message = 'must contain at least two special characters';
break;
}
break;
}
});
return errors;
}),
然后获取所有消息:
passwordSchema.validate(data, { abortEarly: false });