问题描述
我想在调用注册 API 时同时获取所有错误。在这里,我遵循 MVC 结构,因此我必须使用验证文件在那里存储 joi 验证 我的验证文件:
const Joi = require("@hapi/joi");
function registerValidate(req) {
let schema = Joi.object({
fname: Joi.string().required().empty().messages({
"string.base": `first name should be a type of 'text'`,"string.empty": `first name cannot be an empty field`,"any.required": `first name is a required field`,}),lname: Joi.string().required().empty().messages({
"string.base": `last name should be a type of 'text'`,"string.empty": `last name cannot be an empty field`,"any.required": `last name is a required field`,email: Joi.string().required().empty().email().messages({
"string.base": `email should be a type of 'text'`,"string.empty": `email cannot be an empty field`,"string.email": `email format not valid`,"any.required": `email is a required field`,password: Joi.string().required().empty().regex(/^[a-zA-Z0-9]{6,16}$/).min(6).max(16).messages({
"string.base": `password should be a type of 'text'`,"string.empty": `password cannot be an empty field`,"string.min": "password should be of minimum 6 characters","string.max": "password should be of maximum 16 characters","string.pattern.base": "password must contains lower case,upper case and between 6 and 16 characters","any.required": `password is a required field`,confirm_password: Joi.string().required().valid(Joi.ref('password')).messages({
"string.base": `confirm password should be a type of 'text'`,"any.only": "confirm password doesn't match password","any.required": `confirm password is a required field`,})
const options = {
abortEarly: false,// include all errors
};
return schema.validate(req,options);
}
module.exports = {
registerValidate
};
我调用验证的控制器:
const {registerValidate}=require('../validations/authValidation')
在注册 API 中:
let { error } = registerValidate(req.body);
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)