I'm creating a multi step form and I want to raise an error if my field 'title' and invited[0].name( at least one invited should be written) are not filled in my form such as 'this field is required' in red under the input box. I use Yup but doesn't seem working... Any ideas ?
export default function Information() {
const [userData, setUserData] = useState({});
const handleChange = (e) => {
const { value, checked } = e.target;
setUserData((userData) => ({
...userData,
[value]: checked
}));
};
return (
<div className="flex flex-col ">
<div>
Title :
<input
onChange={handleChange}
value={userData["title"]}
name="title"
placeholder="Title"
/>
</div>
...
);
}
In validation.js :
import * as Yup from "yup";
import menus from "../data/menus.json";
const {
menus: { title, invited }
} = menus;
export default [
Yup.object().shape({
[title]: Yup.string().required(`Title required`),
[invited.name]: Yup.string().required(`At least one participant required`)
})
];
menus.json:
{
"menus": [
{
"id": "Menu1",
"title": "Soup",
"price": 4,
"invited": [
{
"name": "Jose Luis",
"location": "LA"
},
{
"name": "Smith",
"location": "New York"
}
]
},
...
}
Here is my sandboxLink
Yup.array() to define the schema for the array (invited) and .of() to
target each item of the array (which is an object in your case).Change the validation.js to
import * as Yup from "yup";
import menus from "../data/menus.json";
const {
menus: { title, invited }
} = menus;
export default Yup.object().shape({
title: Yup.string().required(`Title required`),
invited: Yup.array()
.of(
Yup.object().shape({
name: Yup.string().required('Required') // these constraints take precedence
})
)
.required('At least one participant required') // these constraints are shown if and only if inner constraints are satisfied
.min(1, 'At least one participant required'),
});