25 Jan 2023

Implementing real-time form validation in a React application

Form validation is a crucial aspect of web development, as it ensures that the data submitted by users is accurate and complete. In a React application, real-time form validation can be implemented using a combination of controlled inputs and validation logic.

The first step in implementing real-time form validation is to create controlled inputs. In React, a controlled input is an input element whose value is controlled by the component's state. To create a controlled input, you can use the value and onChange props to link the input element's value to the component's state.

For example, let's say we have a simple form with a text input for a user's name. To create a controlled input for this form, we can use the following code:

import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');

  return (
    <form>
      <label>
        Name:
        <input type="text" value={name} onChange={event => setName(event.target.value)} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

In this example, the value prop of the input element is set to the component's name state variable, and the onChange prop is set to a function that updates the name state variable with the value of the input element.

Next, we can add validation logic to our form. This can be done by creating a function that checks the value of the form inputs and returns an error message if the input is invalid. For example, we can add a validation function that checks if the name input is empty:

function validateName(name) {
  if (!name) {
    return 'Name is required';
  }
}

We can then call this function in our component and display the error message if the input is invalid:

import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');
  const [error, setError] = useState(null);

  const handleSubmit = event => {
    event.preventDefault();
    const error = validateName(name);
    setError(error);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={event => setName(event.target.value)} />
        {error && <p>{error}</p>}
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

In this example, we added a handleSubmit function that is called when the form is submitted. The function calls our validateName function and sets the component's error state variable with the error message returned by the validation function. We also added a p element to display the error message if it exists.

We can also use the same validation function on the onChange event of the input field, this way user will get the error message as soon as they type something wrong in the input field, this will give real-time validation to the user.

import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');
  const [error, setError] = useState(null);

  const handleSubmit = event => {
    event.preventDefault();
    const error = validateName(name);
    setError(error);
  }
  const handleChange = event => {
    const error = validateName(event.target.value);
    setName(event.target.value);
    setError(error);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
        {error && <p>{error}</p>}
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

In this example, we added an handleChange function that is called when the input field is changed. The function calls our validateName function and sets the component's error state variable with the error message returned by the validation function.

This is a simple example of how real-time form validation can be implemented in a React application. Of course, in a real-world application, you would likely have multiple inputs and more complex validation logic. But the basic principles remain the same: use controlled inputs and validation functions to ensure that the data submitted by users is accurate and complete.

In conclusion, Form validation is an important aspect of web development, and by using the combination of controlled inputs and validation logic, we can easily implement real-time form validation in a React application. This will give a better user experience by showing errors in real-time and also ensures that the data submitted is accurate and complete.