Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Implementar mensaje de validación para reaccionar-gancho-forma

Intento implementar un formulario con react-hook-form . Intenté esto:

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

Código de página completa:

https://pastebin.com/KZzsLZAn

Cuando envío el formulario, envío un mensaje POST usando:

 import axios from "axios"; import React from "react"; const baseURL = "https://jsonplaceholder.typicode.com/posts"; export const SubmitContact = (json) => { return axios.post(baseURL, json); };

Pero no hay un mensaje de validación en el formulario ni un mensaje final de que el formulario se ha completado correctamente.

¿Sabes cómo puedo implementar esta funcionalidad?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Intente obtener los errors de useForm así:

 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 Report

0

Para mostrar el mensaje de error:

 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>

Para restablecer el formulario después del envío:

 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 Report

0

No está utilizando las rules correctamente en el componente Controller , no necesita definir el nombre de la entrada registrada, solo tiene que decir reglas:

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

Para acceder a estos mensajes de error, debe usar formState de useForm

 const {formState: {errors}} = useForm() // accessing errors {errors.country?.message}

Para borrar el formulario, simplemente use reset

Aquí hay un entorno limitado de trabajo de su código: https://codesandbox.io/s/late-haze-jivrwp?file=/src/App.js

Al enviar, puede ver que aparece el error en el campo del país

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!