Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

So based on your codes, here is what you need to do:

const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setError
  } = useForm();
  const onSubmit = (data) => console.log(data);

  useEffect(() => {
    const db = watch("dob");
    if (db) {
      const dbDate = new Date(db).getFullYear();
      const currentDate = new Date().getFullYear();
      const age = currentDate - dbDate;
      if (age < 5) {
        setError("dob", {
          type: "too young",
          message: "Sorry bro! you're too young to use this ;)"
        });
      }
    }
  }, [watch("dob")]);

and then use the error wherever you wish:

{errors?.dob?.type === "too young" && (
            <p style={{ color: "red" }}>{errors.dob.message}</p>
          )}

here is a working demo to show how it's look like: https://codesandbox.io/s/funny-surf-d4gtt?file=/src/App.js:2336-2453

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda