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

时间:2019-10-17 05:30:18

标签: javascript node.js validation 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

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

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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);
};
相关问题