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

111
Visualizações
Implement validation message for react-hook-form

I ant to implement a form with react-hook-form. I tried this:

....
 <form onSubmit={handleSubmit(onSubmit)} className='mt-4 register-form'>
            <div className='row'>
              <div className='col-sm-6'>
                <div className='input-group mb-3'>
                  <Controller
                      control={control}
                      name={"name"} //  the key of json
                      defaultValue={""}
                      render={({ field }) => (
                          <input
                              {...field}
                              type="text"
                              className="form-control"
                              placeholder="Name"
                              aria-label="name"
                              onChange={(e) => field.onChange(e.target.value)}
                          />
                      )}
                  />
                </div>
              </div>
.....

Full page code:

https://pastebin.com/KZzsLZAn

When I submit the form I send a POST message using:

import axios from "axios";
import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export const SubmitContact = (json) => {
    return axios.post(baseURL, json);
};

But there is no validation message into the form and no final message that the form is successfully summitted.

Do you know how I can implement this functionality?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Try getting the errors from useForm like so:

const { errors, ...rest } = useForm();

<div className="col-sm-6">
  <div className="input-group mb-3">
    <Controller
      control={control}
      name={"name"} //  the key of json
      defaultValue={""}
      rules={{ name: { required: true } }}
      render={({ field }) => (
        <input
          {...field}
          type="text"
          className="form-control"
          placeholder="Name"
          aria-label="name"
          onChange={(e) => field.onChange(e.target.value)}
        />
      )}
    />
    {errors.name && (
      <div className="alert alert-danger">{errors.name.message}</div>
    )}
  </div>
</div>;
about 4 years ago · Santiago Trujillo Relatório

0

To display error message:

const { errors, control, handleSubmit } = useForm();

...

<form onSubmit="{handleSubmit(onSubmit)}" className="mt-4 register-form">
  <div className="row">
    <div className="col-sm-6">
      <div className="input-group mb-3">
        <Controller 
          control={control} 
          name="name"
          defaultValue="" 
          render={({ field }) => ( 
            <input 
             {...field} 
             type="text"
             className="form-control" 
             placeholder="Name" 
             aria-label="name"
             onChange={(e) => field.onChange(e.target.value)} 
            /> 
           )} 
         />
         {errors.name && <p>{errors.name.message}</p>}
      </div>
    </div>
  </div>
</form>

To reset the form after submission:

const { errors, control, reset, handleSubmit } = useForm();

...

const onSubmit = (formData) => {
    try {
      SubmitContact(formData).then((res) => {
        setPost(res.data);
        reset();
      });
    } catch (e) {
      console.error(e);
    }
};
about 4 years ago · Santiago Trujillo Relatório

0

You are not using the rules correctly in Controller component, you don't need to define the name of registered input, you just have to say rules:

rules={{ 
   required: "Required", // Note you are wrapping this inside a key which is not required
}}

To access this error messages, you need to use formState from useForm

const {formState: {errors}} = useForm()

// accessing errors
{errors.country?.message}

In order to clear form just use reset

Here's a working sandbox of your code: https://codesandbox.io/s/late-haze-jivrwp?file=/src/App.js

On submit you can see the error popping up on country field

about 4 years ago · Santiago Trujillo 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