How to Make Form Validation with React JS

Created by Ahmad Negm

2023-04-22

thumbnails
thumbnails
thumbnails

How to Make Form Validation with React JS

Form validation is a process of checking the input values in a form to make sure they are valid. This is important to ensure that the data entered into the form is correct and complete.

In React JS, form validation can be implemented using the

1useForm
hook from the
1react-hook-form
library. The
1useForm
hook takes a number of props, including:

  • 1initialValues

    : The initial values of the form fields.

  • 1onSubmit

    : A function that is called when the form is submitted.

Here is an example of how to use the

1useForm
hook:

1JavaScript

1import React, { useState, useEffect } from "react";
2import { useForm } from "react-hook-form";
3
4const App = () => {
5  const [form, { values, isValid, handleSubmit }] = useForm({
6    initialValues: {
7      name: "",
8      email: "",
9      password: "",
10    },
11  });
12
13  const handleChange = (e) => {
14    form.setValues({
15      [e.target.name]: e.target.value,
16    });
17  };
18
19  const handleSubmit = (e) => {
20    e.preventDefault();
21
22    if (isValid) {
23      // Do something with the form values
24    } else {
25      // Show the errors
26    }
27  };
28
29  return (
30    <form onSubmit={handleSubmit}>
31      <input
32        type="text"
33        placeholder="Name"
34        name="name"
35        value={values.name}
36        onChange={handleChange}
37      />
38      <input
39        type="email"
40        placeholder="Email"
41        name="email"
42        value={values.email}
43        onChange={handleChange}
44      />
45      <input
46        type="password"
47        placeholder="Password"
48        name="password"
49        value={values.password}
50        onChange={handleChange}
51      />
52      <button type="submit">Submit</button>
53    </form>
54  );
55};
56
57export default App;

This code will create a form with three fields: name, email, and password. The form will be validated when the user clicks on the submit button. If the form is valid, the submit function will be called. If the form is not valid, the errors will be displayed.

Here are some other tips for form validation with React JS:

  • Use regular expressions to validate the input values.

  • Use a library like

    1react-hook-form

    to make form validation easier.

  • Display the errors in a clear and concise way.

  • Allow the user to correct the errors and resubmit the form.

Sources

1.  github.com/gengue/hbp-react-auth-template

2.  github.com/SlagterJ/feedingcasino subject to license (MIT)