使用 Joi 进行多次验证

Multiple validations with Joi

我是 Joi 验证的新手,需要您的帮助。我正在努力实现以下目标:

  1. 获取 Joi 中所需的 Postman 中所有空字段的错误消息

  2. 要求用户在点击 PATCH 请求时输入所有或一个有效值。

我试过这个:

  1. 当邮递员中所有字段都为空时(当我没有发送请求时)当一个字段为空时返回错误消息我仍然收到第一个字段的错误但我想要所有空字段的错误消息列表.

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());
    }
  }
}

响应处理程序Class

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; 

邮递员回复

非常感谢您的帮助。谢谢

您只是在发送第 0 个元素,这就是为什么您只收到一个错误的原因。

而不是 error.details[0].message 使用

(error.details || []).map(e=>e.message)

解释:
Joi 将所有错误存储在 error.details 数组中。您只需使用您喜欢的值按照自己的方式格式化即可。

例如这个对象:

{
  first_name: null,
  last_name: null,
  email: null,
  password: null
}

错误是:

[ { message: 'first_name must be a string',
    path: [ 'first_name' ],
    type: 'string.base',
    context: { value: null, key: 'first_name', label: 'first_name' } },
  { message: 'last_name must be a string',
    path: [ 'last_name' ],
    type: 'string.base',
    context: { value: null, key: 'last_name', label: 'last_name' } },
  { message: 'email must be a valid email',
    path: [ 'email' ],
    type: 'string.base',
    context: { value: null, key: 'email', label: 'email' } },
  { message:
     'password must be at least 8 characters long containing 1 capital letter, 1 small letter, 1 digit and 1 of these special characters(@, $, !, %, *, ?, &)',
    path: [ 'password' ],
    type: 'string.base',
    context: { value: null, key: 'password', label: 'password' } } ]