如何在Joi中添加自定义验证器功能? [英] How to add custom validator function in Joi?

查看:113
本文介绍了如何在Joi中添加自定义验证器功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Joi模式,并想添加一个自定义验证器来验证数据,而默认的Joi验证器是无法实现的.

I have Joi schema and want to add a custom validator for validating data which isn't possible with default Joi validators.

当前,我正在使用Joi的16.1.7版本

Currently, I'm using the version 16.1.7 of Joi

   const method = (value, helpers) => {
      // for example if the username value is (something) then it will throw an error with flowing message but it throws an error inside (value) object without error message. It should throw error inside the (error) object with a proper error message

      if (value === "something") {
        return new Error("something is not allowed as username");
      }

      // Return the value unchanged
      return value;
    };

    const createProfileSchema = Joi.object().keys({
      username: Joi.string()
        .required()
        .trim()
        .empty()
        .min(5)
        .max(20)
        .lowercase()
        .custom(method, "custom validation")
    });

    const { error,value } = createProfileSchema.validate({ username: "something" });

    console.log(value); // returns {username: Error}
    console.log(error); // returns undefined

但是我无法以正确的方式实现它.我阅读了Joi的文档,但似乎让我有些困惑.有人可以帮我弄清楚吗?

But I couldn't implement it the right way. I read Joi documents but it seems a little bit confusing to me. Can anyone help me to figure it out?

推荐答案

您的自定义方法必须是这样的:

Your custom method must be like this:

const method = (value, helpers) => {
  // for example if the username value is (something) then it will throw an error with flowing message but it throws an error inside (value) object without error message. It should throw error inside the (error) object with a proper error message

  if (value === "something") {
    return helpers.error("any.invalid");
  }

  // Return the value unchanged
  return value;
};

文档:

https://github.com/hapijs/joi/blob/master/API.md#anycustommethod-description

输出值:

{ username: 'something' }

错误输出:

[Error [ValidationError]: "username" contains an invalid value] {
  _original: { username: 'something' },
  details: [
    {
      message: '"username" contains an invalid value',
      path: [Array],
      type: 'any.invalid',
      context: [Object]
    }
  ]
}

这篇关于如何在Joi中添加自定义验证器功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆