How to do nested object validation with Yup in React JS

Viewed 19

const initialValues = { institute_id: auth.user.id, added_by: "schoolAdmin", post_title: "", description: "", to_whom: "", group_id: [], disable_comments: false, event_type: {}, personalpost_flag: false, start_time: new Date(), end_time: new Date(), location: "", due_date: "", price: "", sales_tax: "", colours: [], sizes: [], fileuploaded: "", member_id: "", rsvp: false, paid_events: false, };

const validationSchema = Yup.object().shape({ post_title: Yup.string().label("title").strict(true).trim().max(30, "First name should be less than 30 chars").required(MESSAGE.REQUIRED), description: Yup.string().required(MESSAGE.REQUIRED), group_id: Yup.array().required().min(1, "Must be a member of atleast one group"), fileuploaded: Yup.mixed().required(MESSAGE.REQUIRED).test("fileFormat", "Unsupported Format", (value) => { if (typeof value === "string") return true; else return !value || (value && SUPPORTED_FORMATS.includes(value.type));
}).test("fileSize", "File too large (max size 5MB)", (value) => { console.log(value); if (typeof value === "string" || typeof value === "undefined") return true; else return value && value.size <= 5000000; }), event_type: Yup.object() .when('calendar', { is: true, then: Yup.object().shape({ start_time: Yup.date().required(MESSAGE.REQUIRED), end_time: Yup.date().required(MESSAGE.REQUIRED), location: Yup.string().required(MESSAGE.REQUIRED), rsvp: Yup.boolean().required(MESSAGE.REQUIRED), paid_events: Yup.object() .when('paid_event', { is: true, then: Yup.object().shape({ paid_event_amount: Yup.string().required(MESSAGE.REQUIRED), paid_event_date: Yup.string().required(MESSAGE.REQUIRED), }), }), }) .when('merchandise', { is: true, then: Yup.object().shape({ price: Yup.string().strict(true).trim(NOSPACE).required(MESSAGE.REQUIRED), sales_tax : Yup.string().strict(true).trim(NOSPACE).required(MESSAGE.REQUIRED), sizes : Yup.string().strict(true).trim(NOSPACE).required(MESSAGE.REQUIRED), colours : Yup.string().strict(true).trim(NOSPACE).required(MESSAGE.REQUIRED), }), }), }), });

0 Answers
Related