How to throw an error when the age is less than 5 years in react useHookForm hook

In the form I have one date-picker. From the date-picker the user is selecting the date of birth. I want to throw an error, if the age is less than five years from the current date. Suppose the user selects year 2015, then it should throw an error.

<div class="input-group date" data-provide="datepicker">
              <input
                {...register("dob", {
                  required: true,
                })}
                type="date"
                id="birthday"
                min="1899-01-01"
                max="2000-13-13"
                class="form-control"
                onClick={set}
              />
              {errors?.dob?.type === "required" && (
                <p>This field is required</p>
              )}
              <div class="input-group-addon">
                <span class="glyphicon glyphicon-th"></span>
              </div>
            </div>

Answer

You should define a custom validate function to check the selected date and pass it to the register section.

A bare minimal example:

const validateDate = (value) => {
    const selected = new Date(value).getFullYear();
    const now = new Date().getFullYear();
    return now - selected >= 5;
  };

...

<input
     {...register("dob", {
          required: true,
          validate: validateDate
        })}
     type="date"
     id="birthday"
     min="1899-01-01"
     max="2000-13-13"
     class="form-control"
     onClick={set}
/>
{errors?.dob?.type === "required" && (
    <p>This field is required</p>
)}
{errors?.dob?.type === "validate" && <p>Invalid date</p>}

CodeSandbox