Joi的多次验证

时间:2019-11-05 13:31:11

标签: node.js 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());
    }
  }
}

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; 

邮递员回复

Postman's response body

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:1)

您只是在使用发送第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' } } ]