I try to do validation between two fields. foo
and bar
.
I try to do it with
.when("bar", { is: (v) => !!v, then: Joi.string().required() }),
But doesn't work the error
return undefined
.
Any idea how to solve that?
const Joi = require("joi");
console.clear();
const schema = Joi.object({
foo: Joi.string()
.allow("", null)
.optional()
.min(2)
.max(10)
.when("bar", {
is: (v) => !!v,
then: Joi.string().required()
}),
bar: Joi.string().allow("", null).optional().min(2).max(10)
});
const { error } = schema.validate(
{ foo: null, bar: null },
{ allowUnknown: true, abortEarly: false }
);
const { error: error2 } = schema.validate(
{ foo: null, bar: "text" },
{ allowUnknown: true, abortEarly: false }
);
console.log({ error }); // should be with error.
console.log({ error2 }); // should be undefiend.
if (error) {
const { details } = error;
console.log({ details });
}
if (error2) {
const { details } = error2;
console.log({ details });
}
This how you need to configure to achieve that
empty(['', null])
, considers ''
and null
as undefined
. or("foo", "bar")
, makes one of them is required. const schema = Joi.object({ foo: Joi.string().empty(['', null]).min(2).max(10), bar: Joi.string().empty(['', null]).min(2).max(10) }).or("foo", "bar");
This is how it's done with Joi :
const schema = Joi.object({
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password')
})
.with('password', 'repeat_password')
const { error } = schema.validate({ password: 'BlaBlaaa', repeat_password: 'Bla' })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.