I need to add rules to the inputs automatically. I want to get the object and add the rules, more or less like the code below, but that doesn't work and I can't do something similar.
Can anyone give me any ideas?
const [form] = Form.useForm();
form.getFieldInstance("username").rules=[
{
required: true,
message: 'Please input your username!',
},
];
Try converting field rules to state array:
const [form] = Form.useForm()
const [formItemRules, setFormItemRules] = useState([])
// find the best moment to update rules
setFormItemRules(() => ([{
required: true,
message: 'Please input your username!'
}]))
<Form.Item
label={'...'}
name={'...'}
rules={ formItemRules }
>
<Input />
</Form.Item>
You can also use an object holding all your form items rules:
const [formRules, setFormRules] = useState({
username: [],
otherField: []
})
setFormRules((current) => ({
...current,
username: [{
required: true,
message: 'Please input your username!'
}]
}))
<Form.Item
label={'...'}
name={'...'}
rules={ formRules.username }
>
<Input />
</Form.Item>