【问题标题】:How to add custom validator function in Joi?如何在 Joi 中添加自定义验证器功能?
【发布时间】:2020-02-13 22:54:13
【问题描述】:

我有 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

但我无法以正确的方式实现它。我阅读了 Joi 文档,但对我来说似乎有点困惑。谁能帮我弄清楚?

【问题讨论】:

    标签: javascript node.js validation express joi


    【解决方案1】:

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

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

    【讨论】:

    • @ShifutHossain 我试过了,它给出了错误 [ValidationError]: "username" contains an invalid value]
    • 您在本地计算机上试过了吗?
    • @ShifutHossain 我知道 joi 在浏览器中不兼容,您可以签入您的节点应用程序吗?
    • 在节点应用程序中使用时,我将输出添加到答案中。这不是你想要的吗?
    【解决方案2】:
    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'
    });
    

    【讨论】:

    • 嗯,类型说helper.message 的第一个参数必须是Record&lt;string, string&gt;,而不是string...
    • 你可以忽略类型错误...但我认为它应该在最后返回value而不是true
    • 修复类型问题返回helper.message({custom: 'put error message here'})
    【解决方案3】:

    这就是我验证我的代码的方式,看看它并尝试格式化你的代码

    const busInput = (req) => {
      const schema = Joi.object().keys({
        routId: Joi.number().integer().required().min(1)
          .max(150),
        bus_plate: Joi.string().required().min(5),
        currentLocation: Joi.string().required().custom((value, helper) => {
          const coordinates = req.body.currentLocation.split(',');
          const lat = coordinates[0].trim();
          const long = coordinates[1].trim();
          const valRegex = /-?\d/;
          if (!valRegex.test(lat)) {
            return helper.message('Laltitude must be numbers');
          }
          if (!valRegex.test(long)) {
            return helper.message('Longitude must be numbers');
          }
        }),
        bus_status: Joi.string().required().valid('active', 'inactive'),
      });
      return schema.validate(req.body);
    };
    

    【讨论】:

    • 虽然这可能会回答这个问题,但如果可能的话,您应该edit 回答您的回答,以包含对如何此代码块回答问题的解释。这有助于提供上下文,并使您的答案对未来的读者更有用。
    • message() 的第一个参数是LanguageMessages,即Record&lt;string, string&gt;
    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2019-03-21
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多