skip to Main Content

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


  1. 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

    fileSize: (file) => {
      if (file === null) return true;
      return (
        file?.size < 2000100 &&
        "File size shouldn't be more than 2MB!"
       );
    },
    

    There is a closed issue about this in the react-hook-form github https://github.com/react-hook-form/react-hook-form/issues/1781

    Login or Signup to reply.
  2. 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.

    import { useEffect } from "react";
    import { useForm } from "react-hook-form";
    
    type FieldInputs = {
      requiredInput: string;
      optionalInput: string;
    };
    
    export const WatchExample = () => {
    
      const { watch, register } = useForm<FieldInputs>();
      const HasInput = watch("requiredInput");
    
      return (
        <div>
          <input {...register("requiredInput", { required: true })} />
          <input
            type="text"
            {...register("optionalInput", {
              required: HasInput?.length > 1 ? true : false,
            })}
          />
          {HasInput?.length > 1 && <div>Only show when input is given </div>}
        </div>
      );
    };
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search