【发布时间】:2020-03-01 21:22:25
【问题描述】:
我刚开始使用 Joi 验证,需要您的帮助。我正在努力实现以下目标:
获取 Postman 中所有空字段的错误消息,这些字段在 Joi 中是必需的
请求用户在点击 PATCH 请求时输入所有或一个有效值。
我试过这个:
- 当一个字段为空时返回错误消息,当邮递员中的所有字段为空时(当我不发送请求时)我仍然收到第一个字段的错误但我想要所有空字段的错误消息列表。
Joi 用户注册验证
import Joi from "joi";
export const validateSignup = user => {
const schema = Joi.object().keys({
first_name: Joi.string()
.min(3)
.max(20)
.required()
.error(() => "first_name must be a string"),
last_name: Joi.string()
.min(3)
.max(20)
.required()
.error(() => "last_name must be a string"),
email: Joi.string()
.email({ minDomainAtoms: 2 })
.trim()
.required()
.error(() => "email must be a valid email"),
password: Joi.string()
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
)
.required()
.error(
() =>
"password must be at least 8 characters long containing 1 capital letter, 1 small letter, 1 digit and 1 of these special characters(@, $, !, %, *, ?, &)"
)
});
const options = { abortEarly: false };
return Joi.validate(user, schema, options);
};
注册控制器
import { validateSignup } from "../helpers/userValidator";
class User {
static async SignUp(req, res) {
const { error } = validateSignup(req.body);
if (error) {
return res
.status(400)
.json(new ResponseHandler(400, (error.details || []).map(er => er.message), null).result());
}
}
}
ResponseHandler 类
class ResponseHandler{
constructor(status, message, data, error){
this.status = status;
this.message = message;
this.data = data,
this.error = error;
}
result(){
const finalRes = {};
finalRes.status = this.status;
finalRes.message = this.message;
if(this.data !== null){
finalRes.data = this.data;
}else if(this.error !== null){
finalRes.error = this.error;
}
return finalRes;
}
}
export default ResponseHandler;
邮递员回复
感谢您的帮助。谢谢
【问题讨论】: