joi icon indicating copy to clipboard operation
joi copied to clipboard

Field validation

Open hbindiya opened this issue 8 months ago • 3 comments

Support plan

  • is this issue currently blocking your project? (yes/no): yes
  • is this issue affecting a production system? (yes/no): yes

Context

  • node version: v18.14.2
  • module version: 17.3.0
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, ...): both

How can we help?

const NewUser = Joi.object()
  .keys({
    email: Joi.string()
      .email()
      .example("[email protected]"),
    name: Joi.string().example("john doe"),
    username: Joi.when("email", {
      is: Joi.exist(),
      then: Joi.string().required(),
      otherwise: Joi.optional()
    }).example("johndoe"),
    password: Joi.when("email", {
      is: Joi.exist(),
      then: Joi.string().required(),
      otherwise: Joi.optional()
    }).example("password"),
    "first-name": Joi.string()
      .allow(null)
      .example("john"),
    "communication-email": Joi.string()
      .allow(null)
      .example("[email protected]"),
    "phone-number": Joi.number()
      .allow(null)
      .example(9898989898),
    "avatar-s3-key": Joi.string()
      .allow(null)
      .example("ace/2018-12/89a3fa9c-0b79-4140-b0ef-d1a35ea0b733/dog4.jpeg"),
    "last-name": Joi.string()
      .allow(null)
      .example("doe"),
    "dont-login": Joi.boolean()
      .allow(null)
      .example(true),
    "avatar-url": Joi.string()
      .uri()
      .allow(null)
      .example(
        "https://thumbor-stg.assettype.com/ace/2018-12/89a3fa9c-0b79-4140-b0ef-d1a35ea0b733/dog4.jpeg"
      ),
    "login-phone-number": Joi.string().example("+919898989898"),
    otp: Joi.string()
      .when("login-phone-number", {
        is: Joi.exist(),
        then: Joi.required(),
        otherwise: Joi.optional()
      })
      .when("email", {
        is: Joi.exist(),
        then: Joi.required(),
        otherwise: Joi.optional()
      })
      .example("12345"),
    metadata: Joi.object()
      .example({ "favorite-fruit": "papaya" })
      .meta({ swagger: { deprecated: true } }),
    active: Joi.boolean().example(true)
  })
  .xor("otp", "username", "password")
  .or("login-phone-number", "email");
For payload:
{
    "email":"[email protected]",
    "otp": "913676"
}
Response:
{
    "message": "\"body.username\" is required,\"body.password\" is required"
}

username and password was initially to be mandatory, but when I have otp, username+password can be optional and vice versa. it can also allow all the three fields.

hbindiya avatar Nov 02 '23 01:11 hbindiya