React Tips — Form Validation

John Au-Yeung
May 20, 2020 · 4 min read
Photo by Heather Lo on Unsplash

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.

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.

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 .

Photo by Fredrik Öhlander on Unsplash

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.

The Startup

Get smarter at building your thing. Join The Startup’s +793K followers.

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

John Au-Yeung

Written by

Web developer. Subscribe to my email list now at https://thewebdev.info/subscribe/. Email me at hohanga@gmail.com

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +793K followers.

John Au-Yeung

Written by

Web developer. Subscribe to my email list now at https://thewebdev.info/subscribe/. Email me at hohanga@gmail.com

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +793K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store