如何在 Joi 中添加自定义验证器功能?

Shi*_*ain 10 javascript validation node.js express joi

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

目前,我使用的是 Joi 16.1.7 版本

   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
Run Code Online (Sandbox Code Playgroud)

但我无法以正确的方式实施它。我阅读了 Joi 文档,但对我来说似乎有点混乱。任何人都可以帮我弄清楚吗?

Sul*_*Sah 14

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

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

Run Code Online (Sandbox Code Playgroud)

文档:

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

输出值:

{ username: 'something' }
Run Code Online (Sandbox Code Playgroud)

错误输出:

[Error [ValidationError]: "username" contains an invalid value] {
  _original: { username: 'something' },
  details: [
    {
      message: '"username" contains an invalid value',
      path: [Array],
      type: 'any.invalid',
      context: [Object]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)


小智 14

const Joi = require('@hapi/joi');

Joi.object({
    password: Joi
        .string()
        .custom((value, helper) => {

            if (value.length < 8) {
                return helper.message("Password must be at least 8 characters long")

            } else {
                return true
            }

        })

}).validate({
    password: '1234'
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以忽略类型错误...但我认为它应该在最后返回“value”而不是“true” (3认同)
  • 如果您在“if”子句中返回,则实际上并不需要“else”语句,尽管我建议使用注释和“// else”来提高可读性 (3认同)