How to validate an Ant Design Form.List to limit the max number of fields.
In order to limit the number of maximum fields allowed inside the Form.List component, we need to create a custom validator inside the "rules" prop specifying the conditions and the error message.
We will begin with an example of how a normal Form.List can be implemented. The following code is taken from the Ant Design's Form.List Dynamic Form nest Items section.
This has the normal functionality of adding new fields and removing existing ones. This is what the default UI would be like:
How to show error/warning when the field count exceeds a limit?
When using, the Form.List component, we cannot add the normal "rules" properties like "required", "message", etc to the component for validation. Instead, we need to pass a custom validator.
Let's say we need to limit the number of fields to a total of 5. In that case, our custom validator can be implemented as the following :
validator:async(_, names)=>{if(names.length>=6){returnPromise.reject(newError("Exceeded maximum rubric field. (Max is 7)"));}},
We need to pass this custom validator to the "rules" prop as a property. The full implementation is as follows:
Whenever the field count exceeds 5, an error will be triggered with the message we provided in the custom validator. This will also restrict the form from submitting just like normal validation.
How to set a minimum number of fields by default in the Form.List?
In order to have a specific set of fields initialized by default, we need to pass in the field values to "initialValue" prop of the Form.List component. Check the following article to learn more about it
Subscribe to Sharooq
Join the growing community of friendly readers through my monthly newsletter.
Could not sign up! Invalid sign up link.
Subscribe to Sharooq
Stay up to date! Join my monthly newsletter and get the latest productivity tips, engineering advancements and practical life advice directly to your inbox.