I created a custom Yup validation using .test()
.
// users is an array of strings
user: Yup.string().test(
"user-check",
"At lease one user should be added",
() => users.length > 0
)
The goal is to validate the form when at least one user is added. An input field let you type a username (any string value) then you click a button to add it to a list.
The validation is working well after adding the 2nd username (or adding the 1st one then start typing on the field). I'm sharing this live Demo: https://codesandbox.io/s/hopeful-goldwasser-shpbk
Steps to reproduce
- Click on the text field.
- Type a username.
- Click the red button.
Expected
- The form should be valid.
What you'll get
- The form is invalid
Any feedback about this strange behavior?
Remark
I'm not sure if this is the origin of the problem.
The first time you add a user, the validation is called 2 times: the 1st time with an empty
users
array and then with the correctusers
value (which is the user you added)!