Peter Penzov
Peter Penzov

Reputation: 1658

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?

Upvotes: 1

Views: 2615

Answers (3)

Fer Toasted
Fer Toasted

Reputation: 1738

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={{ 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>;

Upvotes: 1

Sanket Shah
Sanket Shah

Reputation: 3091

To display error message:

const { control, handleSubmit, formState: { errors } } = 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="" 
          rules={{ 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 && <p>{errors.name.message}</p>}
      </div>
    </div>
  </div>
</form>

To reset the form after submission:

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

...

const onSubmit = (formData) => {
    try {
      SubmitContact(formData).then((res) => {
        setPost(res.data);
        reset();
      });
    } catch (e) {
      console.error(e);
    }
};

Upvotes: 1

Yash Joshi
Yash Joshi

Reputation: 2774

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

Upvotes: 0

Related Questions