Validate array when the subField value chages, how to do it? #743
-
Hi thanks in advance. I have a array, say { people: [{name: 'sam'}] } Now, how do I make sure, that name is unique. I should throw a error message if there are two usernames that are same. This is my implementation, Try clicking on The error is not going away. Validation should run again when I change the internal array items, which is not happening right now. Any help on this would be appreciated. Is there any API that I should use to achieve this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Let's look at the generic case, you have an array of objects and you're trying to run the onChange validator of the parent when values nested in the child are changed. If I got that right, what you'd need here is the onChange validation to bubble up to its parents. Something similar but more precise (validating X while Y changes) can be achieved through Linked Fields but as of today you cannot easily link an entire array at one go. In this specific case I'd go by manually running the validator when changing names but we might think of a new dedicated API for similar cases (like linking to entire arrays at one go). Try by adding <form.Field key={i} name={`people[${i}].name`}>
{(subField) => {
return (
<div>
<label>
<div>Name for person {i}</div>
<input
value={subField.state.value}
onChange={(e) => {
subField.handleChange(e.target.value);
field.validate('change');
}}
/>
</label>
</div>
);
}}
</form.Field> |
Beta Was this translation helpful? Give feedback.
-
Thanks much!! This works great for now..! |
Beta Was this translation helpful? Give feedback.
Let's look at the generic case, you have an array of objects and you're trying to run the onChange validator of the parent when values nested in the child are changed. If I got that right, what you'd need here is the onChange validation to bubble up to its parents.
Something similar but more precise (validating X while Y changes) can be achieved through Linked Fields but as of today you cannot easily link an entire array at one go.
In this specific case I'd go by manually running the validator when changing names but we might think of a new dedicated API for similar cases (like linking to entire arrays at one go).
Try by adding
field.validate('change')
there: