My data structure looks like this:
{
foo: true,
bar: {
baz: [{label: 'mario', url: ''}]
}
}
And my yup
validator looks like this:
const schema = yup.object().shape({
foo: yup.boolean(),
bar: yup.mixed().when('foo', {
is: true,
then: yup.object().shape({
baz: yup.array.of(
yup.object().shape({
label: yup.string.required(),
url: yup.url().required()
})
)
}),
otherwise: yup.object().nullable(true)
})
})
But the validation isn't working for bar.baz
; if foo
is true
, bar never throws an error if it isn't given an array with the required objects.
If I set bar
to validate as something else, say:
bar: yup.mixed().when('foo', {
is: true,
then: yup.string().required()
otherwise: yup.string.nullable(true)
})
It throws an error for bar
as expected. What am I missing?
My data structure looks like this:
{
foo: true,
bar: {
baz: [{label: 'mario', url: 'https://nintendo.'}]
}
}
And my yup
validator looks like this:
const schema = yup.object().shape({
foo: yup.boolean(),
bar: yup.mixed().when('foo', {
is: true,
then: yup.object().shape({
baz: yup.array.of(
yup.object().shape({
label: yup.string.required(),
url: yup.url().required()
})
)
}),
otherwise: yup.object().nullable(true)
})
})
But the validation isn't working for bar.baz
; if foo
is true
, bar never throws an error if it isn't given an array with the required objects.
If I set bar
to validate as something else, say:
bar: yup.mixed().when('foo', {
is: true,
then: yup.string().required()
otherwise: yup.string.nullable(true)
})
It throws an error for bar
as expected. What am I missing?
1 Answer
Reset to default 2when()
only has access to properties at the same level. From the documentation:
mixed.when(keys: string | Array, builder: object | (value, schema)=> Schema): Schema
Adjust the schema based on a sibling or sibling children fields. You can provide an object literal where the key is is value or a matcher function, then provides the true schema and/or otherwise for the failure condition.
That's why your second example works (because bar
and foo
are siblings). One possible solution is to rearrange your data so that foo
and baz
are siblings.
There is at least one issue on Yup's Github and the author suggests passing data is through Yup's context parameter but I don't think that is possible using Formik and the validationSchema
prop, assuming that's what you're using.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745473945a4629258.html
评论列表(0条)