簡體   English   中英

如何在 Joi 中添加自定義驗證器 function?

[英]How to add custom validator function in 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 文檔,但對我來說似乎有點困惑。 誰能幫我弄清楚?

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

您的自定義方法必須是這樣的:

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

Output 值:

{ username: 'something' }

Output 錯誤:

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

這就是我驗證我的代碼的方式,看看它並嘗試格式化你的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM