Reputation: 939
Im using Formik FormArray object and trying to use the validation does not seem to be working.
Here is snippets of my sample form (sorry its not the full code but its all in parent containers) :
const validationSchema = Yup.object().shape({
domains: Yup.array()
.required('Required')
.matches(/^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$/, {
message: 'Invalid Domain',
excludeEmptyString: true,
})
.matches(/(www\.| http: \/\/|https:\/\/)/, {
message: 'Should not contain www.| http:// | https://',
excludeEmptyString: true,
})
})
const ErrorMessage = ({ name }) => (
<Field
name={name}
render={({ form }) => {
const error = getIn(form.errors, name)
const touch = getIn(form.touched, name)
return touch && error ? error : null
}}
/>
)
{
({ handleChange, handleBlur, values, errors, touched }) => (
<FormGroup>
<Label>Domains</Label>
<FieldArray
name="domains"
render={arrayHelpers => (
<>
<ul className="list-unstyled">
{values.domains.map((domain, index, domains) => (
<li className="mb-2" key={index}>
<InputGroup>
<Field
name={`domains[${index}]`}
className="form-control"
/>
<InputGroupAddon addonType="append">
<Button
color="primary"
onClick={() => arrayHelpers.remove(index)}
>
<strong>x</strong>
</Button>
</InputGroupAddon>
<ErrorMessage name={`domains[${index}]`} />
</InputGroup>
</li>
))}
<Button
className="mt-2"
color="secondary"
onClick={() => arrayHelpers.push('')}
>
Add a Domain
</Button>
</ul>
</>
)}
/>
</FormGroup>
I've tried to remove the regex validation and that didn't work. Could anyone recommend how to do this? Thanks
Upvotes: 2
Views: 6370
Reputation: 35
I don't have the reputation to add a comment, but I also had some trouble with arrayHelper and Formik. Is it possible your initial value for the last item in the domains array has not been set to and empty string? If your doing some type of get for initial value it would be comparing and array that is missing the last value that you would be including when submitting domains[${index}]. So in my experience it allows you to submit the form because its you don't have an initial value, unless you are to click on the input which would then set the value to "" or whatever you choose to type.
Upvotes: 0
Reputation: 939
https://jaredpalmer.com/formik/docs/api/fieldarray
The example on the formik site sites for an array of objects:
const schema = Yup.object().shape({
domains: Yup.array()
.of(
Yup.object().shape({
name: Yup.string()
.min(4, 'too short')
.required('Required'), // these constraints take precedence
For accessing an array of strings:
domains: Yup.array().of(
Yup.string()
.trim()
.required('Required')
Upvotes: 1