'React Yup Form Input field validation inside useMemo hook is not working
I have a small snippet of code where a React-Form has an input field in an Edit scenario (where I need to populate the value and allow user to change the value in the input field). Once user change the value in the input field, I need to validate it as per my Yup schema.
Here is my code snippet:
const validator = useMemo(() => {
yup.object().shape({
shareUser: yup.string()
.required("Enter users separated by a semicolon.")
.matches(/^([a-zA-Z0-9~!@#$%^&*()\\\-_. ]+;?)+$/, `Enter users separated by a semicolon.`),
},
)
}, []);
.......
const form = useForm({shareUser: null}, validator);
.......
const handleChange = (event) => {
setCurrentValue(event.target.value); // currentValue is a useState hook.
form.formState.shareUser = event.target.value;
form.dirty['shareUser'] = true;
};
............
<input
name="shareUser"
label="Users"
form={form}
defaultValue={currentValue}
onChange={handleChange }
/>
So my allowed pattern is non-empty strings like "user1;user2" or "user1;". If user types in something like "user1, user2", I am going to reject it with the validation error:
Enter users separated by a semicolon.
However the issue is that: when I am putting my validator inside the useMemo hook, it's not working!
However if I move the validator outside of the useMemo, it's working.
I am not able to figure out what I am missing here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
