【问题标题】:Multiple validations with Joi使用 Joi 进行多重验证
【发布时间】:2020-03-01 21:22:25
【问题描述】:

我刚开始使用 Joi 验证,需要您的帮助。我正在努力实现以下目标:

  1. 获取 Postman 中所有空字段的错误消息,这些字段在 Joi 中是必需的

  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; 

邮递员回复

感谢您的帮助。谢谢

【问题讨论】:

    标签: node.js joi


    【解决方案1】:

    您只是在使用发送 0th 元素,这就是您只收到一个错误的原因。

    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' } } ]
    

    【讨论】:

    • 感谢您的意见。但是,我尝试了您的解决方案,但它仍然给我第一个元素的错误消息。它没有返回整个错误消息数组。
    • 这是不可能的。你在SignUp 函数中写了什么?同时发布ResponseHandler类的相关部分。
    • 看起来不错,我想您在更改后忘记重新启动节点服务器。因为至少它会被包含在[..]中。
    • 我尝试重新启动服务器,但它不起作用。非常感谢,这与我想要的非常接近。我会继续寻找,我现在只是在赶时间。
    • { status: 400, message: [ 'first_name must be a string', 'last_name must be a string', 'email must be a valid email', 'password must be at least 8 characters long containing 1 capital letter, 1 small letter, 1 digit and 1 of these special characters(@, $, !, %, *, ?, &)' ], error: undefined }
    猜你喜欢
    • 2022-01-25
    • 2020-05-11
    • 2020-08-04
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2016-02-19
    • 2020-01-25
    • 2022-11-14
    相关资源
    最近更新 更多