I have a form to create a course with authors. Form with one Author | Form with two Authors
How'd you create a Yup schema for the array of authors? It should be an Array of the Authors (minimum one author, capital Name and Surname).
That's my basic schema, when it was a single input:
const COURSE_SCHEMA = yup.object().shape({
title: yup
.string()
.min(2, 'Too Short!')
.max(16, 'Too Long!')
.required('Required'),
description: yup
.string()
.min(24, 'Too Short!')
.max(124, 'Too Long!')
.required('Required'),
authors: yup.string().required('Required'),
duration: yup
.number('Paste the duartion time in minutes')
.integer('The number has to be integer')
.min(15, 'At least 15 minutes!')
.max(300, 'Maximum duration is 300 minutes!')
.required('Required'),
});
const yupSchemas = {
// loginSchema: LOGIN_SCHEMA,
// registrationSchema: REGISTERATION_SCHEMA,
courseSchema: COURSE_SCHEMA,
};
Formik init:
<Formik
validationSchema={yupSchemas.courseSchema}
initialValues={{
title: '',
description: '',
authors: [''],
duration: '',
}}
//-----------------
That's my dynamic multivalue input. It was made by this Formik's template:
<FormStrap.Group className='mb-3' controlId='course-authors'>
<FormStrap.Label>Authors</FormStrap.Label>
<FieldArray
name='authors'
render={(arrayHelpers) => (
<Box>
{values.authors && values.authors.length > 0 ? (
values.authors.map((authors, index) => (
<Box key={index}>
<Field
className='form-control'
name={`authors.${index}`}
type='text'
placeholder='Name Surname'
/>
<Button
className='mt-1'
variant='success'
size='sm'
onClick={() => arrayHelpers.insert(index, '')}
>
+
</Button>{' '}
<Button
className='mt-1'
variant='danger'
size='sm'
onClick={() => arrayHelpers.remove(index)}
disabled={values.authors.length === 1}
>
-
</Button>
</Box>
))
) : (
<Button onClick={() => arrayHelpers.push('')}>
Add an Author
</Button>
)}
</Box>
)}
/>
</FormStrap.Group>
This one was a right answer. Thanks to Usama.
authors: yup.array().of(yup.string())