I’m working on a form with some optional fields that need to be validated only if an input is entered. However, react hook form returns a validation error even when no inputs. I have also tried to set:
required: {
value: false,
message: "This field is not required"
}
But it still returns a validation error even when no inputs are entered.
Below is the code snippets for one of the fields that need to be validated only if an input is entered.
<div className={styles.formInputFile}>
<label htmlFor="ref_letter">
Reference Letter (For Doctorate and Diploma Courses)
</label>
<Controller
control={control}
name={"reference_letter"}
rules={{
validate: {
fileSize: (file) => {
return (
file?.size < 2000100 &&
"File size shouldn't be more than 2MB!"
);
},
acceptedFormats: (file) => {
return (
["image/png", "image/jpeg", "application/pdf"].includes(
file?.type
) || "Only JPEG, PNG and PDF files are accepted!"
);
},
},
}}
render={({ field: { value, onChange, ...field } }) => {
return (
<input
{...field}
value={value?.fileName}
onChange={(event) => {
onChange(event.target.files[0]);
}}
type="file"
id="rererence_letter"
accept=".png, .jpeg, .pdf"
/>
);
}}
/>
<p>{errors.reference_letter?.message}</p>
</div>
2
Answers
You can check if the field value is empty or equal to the default value and return "true"(i.e. indicate that the field passed validation) in that case.
For example
There is a closed issue about this in the react-hook-form github https://github.com/react-hook-form/react-hook-form/issues/1781
You can get your desired functionality by using watch and setting conditional rules. here is a basic example of doing this, copy this and try it out in a sandbox, it only requires the second input when the first input is given.