i have been trying to create form validation in steps with Antd, but I am struggling with the validation part. My goal is that i cannot click next if fields are not filled correctly. As i understand, i have to make form submit every time I click next, but since I am a beginner i don't know how to do it with nested components. Profile component is nested inside third step. Can you please help me?
const { Step } = Steps;
const steps = [
{
title: 'First',
content: 'First-content',
},
{
title: 'Second',
content: 'Second-content',
},
{
title: 'third',
content: <Profile/>,
},
{
title: 'last',
content: 'Third',
},
];
const ListingSteps = () => {
const [current, setCurrent] = useState(0);
const onChange = current =>{
setCurrent(current)
}
const next = () => {
setCurrent(current + 1);
};
const prev = () => {
setCurrent(current - 1);
};
return (
<>
<Steps current={current} onChange={onChange}>
{steps.map(item => (
<Step key={item.title} title={item.title} />
))}
</Steps>
<div className="steps-content">{steps[current].content}</div>
<div className="steps-action">
{current < steps.length - 1 && (
<Button type="primary" onClick={() => next()}>
Next
</Button>
)}
{current === steps.length - 1 && (
<Button type="primary" onClick={() => message.success('Processing complete!')}>
Done
</Button>
)}
{current > 0 && (
<Button style={{ margin: '0 8px' }} onClick={() => prev()} >
Previous
</Button>
)}
</div>
</>
);
PROFILE
function Profile() {
return(
<>
<Form name="profile" >
<Form.Item name="name" label='Name' rules={[{required:true, message:'Please enter your name' }]}>
<Input/>
</Form.Item>
<Form.Item name="surname" label='Surname' rules={[{required:true, message:'Please enter your name' }]}>
<Input/>
</Form.Item>
</Form>
</>
Use form.validateFields().
When you click on Next button, you can check the all the required fields for current Step by passing all the fields name
in validateFields.
For example, in your Profile Component, you have two Fields: name
& Surname
You can validate the fields by:
const onNext = async () => {
try {
await form.validateFields(['name', 'surname']);
setCurrent((prev)=>prev + 1);
} catch {}
};
Add one more key in each object of step list and pass an array of form field name in for that Step component.
const steps = [
{
title: 'third',
content: <Profile/>,
fields: ['name', 'surname']
},
....
];
Now you can validate each step component by getting each step fields from steps array.
await form.validateFields(steps[current].fields);
Check the FormInstance API: https://ant.design/components/form/#FormInstance