'How can I make error validation work in React Hook Form when using template literal in register function?
I'm using React Hook Form and Typescript to build a collection of forms. I'm building my forms using a configuration object. The configuration object has a key called prop that is of type string that I'm passing to my form's register method.
This works as expected, but the problem I'm having is that errors.prop is returning undefined so the UI for my error validation doesn't appear, though I can see when I console.log the error object that the error is triggering. The error validation is looking for the prop in the register method, but the problem is I don't know how to pass the prop to the error method the way I did in the register function.
Steps to reproduce. Please see my codesandbox. Simply submit the form without adding any text to the forms. You will see in the console that the errors exist, but don't appear in the UI because I'm referencing it improperly in my statement https://codesandbox.io/s/agitated-yonath-8jvvv?file=/src/constants/form.constants.ts:1039-1386
{
question: 76,
label:
"Filer name (Holding company, lead financial institution, or agency, if applicable)",
prop: "question_76",
style: "50%",
type: "text"
},
{
question: 77,
label: "TIN",
prop: "question_77",
style: "20%",
type: "text"
}
<Form style={style ? { width: style } : { width: FormStyle.width }}>
<FormLabel htmlFor={prop}>{question && `${question}.`} {label} {optional && `${optional}`} </FormLabel>
<FormInput {...methods.register(`${prop}` as any, { required: true })} type="text" />
{errors.prop && <span>This field is required</span>}
</Form>
// errors.prop returns undefined
Solution 1:[1]
For anyone else who may come across this issue. The errors are contain within an object and so I filtered them to find the specific one I needed and converted it to a string and tested for equality.
const TextInput = (props: FormInputProps): JSX.Element => {
const { form, register, errors } = props;
const errorMatch = Object.keys(errors).filter((error) => error === form.prop);
return (
<Form style={form.style ? { width: form.style } : { width: FormStyle.width }}>
<FormLabel htmlFor={form.prop}>{form.question && `${form.question}.`} {form.label} {form.optional && `${form.optional}`} </FormLabel>
<FormInput {...register(`${form.prop}` as any, { required: true })} type="text" />
{errorMatch.toString() === form.prop && (<ErrorState>This field is required</ErrorState>)}
</Form>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | London804 |
