Categories
React Tips

React Tips — Form Validation

Spread the love

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps.

In this article, we’ll look at how to do form validation in React apps.

Form Validation and React

Form validation isn’t included in React since it’s just a view library. We’ve to deal with watching form values and form validation ourselves. To make the job easy, we can use a library to do it.

React Hook Form

One easy library that we can use to do form validation is the React Hook Form library.

We can get started by running the following to install it:

npm install react-hook-form

Once we install it, we can use it as follows:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  };

  console.log(watch("name"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="name"
        defaultValue="foo"
        ref={register({ required: true })}
      />
      {errors.name && <span>This field is required</span>}
      <input name="age" ref={register} />
      <input type="submit" />
    </form>
  );
}

In the code above, we used the react-hook-form library to create a form first by using the useForm hook that’s built into react-hook-form to return a few objects that we need to create a form with validation.

Then we create a form with validation by passing in the handleSubmit function into the onSubmit function, which is our submit handler, as the argument.

Then we set the name of the input, which is used for form validation. In the ref prop, we pass in the register function, with the required property set as an optional property to indicate that it’s a required field.

The defaultValue prop lets us set the default value of an input.

If it’s not a field that needs validation, then we just pass in the reference of the register function that’s returned from the useForm hook.

To display error messages, we can get the errors.name variable to get any errors from a field with the given name. In this case, errors.name get the errors from the field with the name attribute set to name .

Then if that’s true , we display an error message.

We can also watch values with the watch function as we have above.

Notice that it doesn’t have any form value handling code. It’s all done by react-hook-form , which is good since it’s less typing for us.

In the end, when we type in something into the input, we’ll see it displayed in the box. When we don’t have anything in the required name input and click Submit, we’ll get an error.

Validation Rules

We can easily change the basic form we have above to include validation rules like number range.

For instance, we can add a number range validation into the age input in the example above as follows:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  };

  console.log(watch("name"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="name"
        defaultValue="foo"
        ref={register({ required: true })}
      />
      {errors.name && <span>This field is required</span>}
      <input
        name="age"
        type="number"
        ref={register({ required: true, min: 0, max: 200 })}
      />
      {errors.age && <span>Age must be between 0 and 200</span>}
      <input type="submit" />
    </form>
  );
}

In the code above, we changed the age input to:

<input
  name="age"
  type="number"
  ref={register({ required: true, min: 0, max: 200 })}
/>

We added the min and max validators and set the input type to number. This way, we get validation of numeric ranges.

Then we added an error display below it which displays when error.age is true .

Conclusion

We can do basic form validation with the react-hook-form package. It lets us easily create forms by using the useForm hook and passing in a few props.

It also handles data binding and form submission without writing our own code to do it.

The package comes with its own validation rules, which can be applied flexibly. We can also watch the values of each field as it changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *