How to define the schema for an array inside the object?
I wanna validate the array use string and number.
the first is string type, then the second is number type.
like this.
const example = {test: ["this is string type", 10]};
const test = {test: ["string", 10]};
// not working
const schema={yup.object().shape({
test: yup.array(yup.string().number()),
}}
The yup is object schema validator, it can't array validation?
@Restoration The ideal way would have been
const yup = require("yup");
const schema = yup.object().shape({
test: yup.array().of(yup.mixed().oneOf([yup.string(), yup.number()]))
});
// Normal Success condition
schema.validateSync({
test: ["this is string type", 10]
});
But unfortunately yup doesn't support one-of-type yet. So the less than ideal way I could propose is
const yup = require("yup");
const schema = yup.object().shape({
test: yup
.array()
.of(
yup.lazy(value =>
typeof value === "number" ? yup.number() : yup.string()
)
)
});
// Normal Success condition
schema.validateSync({
test: ["this is string type", 10]
});
which checks type of value before evaluating it. I think this should help you.
@privateOmega
Thank you! I can solve this problem.
const validationSchema = Yup.object().shape({
myArray: Yup.array().of(
Yup.object().shape({
myProperty: Yup.number().required()
})
),
})
const validationSchema = Yup.object().shape({ myArray: Yup.array().of( Yup.object().shape({ myProperty: Yup.number().required() }) ), })
myPropery???? on your example what is that?
Wondering the same @mylastore re: myProperty ??? Were you able to get it working?
Wondering the same @mylastore re:
myProperty??? Were you able to get it working?
No, it did not worked for me.
Most helpful comment
@Restoration The ideal way would have been
But unfortunately yup doesn't support one-of-type yet. So the less than ideal way I could propose is
which checks type of value before evaluating it. I think this should help you.