web-dev-qa-db-ja.com

Joiでカスタムバリデータ機能を追加する方法

私はJoi Schemaを持っていて、デフォルトのJoi Validatorで不可能なデータを検証するためのカスタムバリデータを追加したいです。

現在、私は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の文書を読みましたが、少し私には混乱しているようです。誰かが私を理解するのを手伝ってくれる?

7
Shifut Hossain

あなたのカスタムメソッドは次のようにする必要があります。

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##custommethod-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]
    }
  ]
}
 _
1
SuleymanSah

これが私のコードを検証した方法で、それを見てあなたのものをフォーマットしようとしています

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);
};
 _
0
Isaac