hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

Joi - Ignore inputs if both blank otherwise require both #2866

Closed Ganjena closed 2 years ago

Ganjena commented 2 years ago

Support plan

Context

How can we help?

I would like to have two user inputs. I would like both to be optional. BUT if EITHER field is used they then both need to be required.

Example:

Should the user not want to input thier name, firstName and lastName it can be null or "" and still pass validation. But if the user inputs EITHER first or last name then BOTH will be required.

My Schema atm:

    const customerSchema = Joi.object({
        name: Joi.object({
            firstName: Joi.string(),
            lastName: Joi.string()
        }).and("firstName", "lastName")
})

With the current Schema the user does need to completed both fields to pass validation BUT they are unable to leave both blank should they choose to.

    const customerSchema = Joi.object({
        name: Joi.object({
            firstName: Joi.string().allow(null, ``),
            lastName: Joi.string().allow(null, ``)
        }).and("firstName", "lastName")
})

With this schema both can now be null or empty but the .and() condition doesnt apply.

The last thing i tried was variation's of .when() but keep coming up with dependancy errors...

    const customerSchema = Joi.object({
        name: Joi.object({
            firstName: Joi.string().when(`lastName`, {is: Joi.exsist(), then: Joi.required(), otherwise: Joi.allow(null,``)}),
            lastName: Joi.string().when(`firstName`, {is: Joi.exsist(), then: Joi.required(), otherwise: Joi.allow(null,``)})
        }).and("firstName", "lastName")
})

Is this possible?

Marsup commented 2 years ago

For now it's not, I need to review https://github.com/hapijs/joi/pull/2762, watch that PR for activity.