Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to do form validation in ReactJS

Understanding Form Validation

Form validation is a significant part of any application development process. It is like a security guard at the door, ensuring that only the right data gets to enter. In the context of a ReactJS application, form validation is an essential task that is performed on the client-side to validate user input before it is sent to the server.

What is Form Validation?

To put it simply, form validation is the process of checking whether the information entered by the user into a form is correct. For instance, if you have a form where users need to enter their email addresses, form validation will ensure that the users enter valid email addresses. If they don't, the form validation process will prompt them to correct their input.

Form validation is like a teacher checking a student's homework. The teacher makes sure the student has done everything correctly before grading. If the student makes a mistake, the teacher points it out and asks the student to correct it. In our case, the form is the homework, and the validation process is the teacher.

Why should we use Form Validation?

Form validation is important for two main reasons:

  • To prevent bad or malicious data from being sent to your server.
  • To improve the user experience by giving feedback and guiding the user to enter correct information.

Imagine a situation where you have a library and you lend books to people. But before you give a book to someone, you check their library card to make sure they are a member. Form validation works in a similar way. It checks the data before it is sent to the server.

Form Validation in ReactJS

ReactJS doesn't have built-in form validation capabilities. But, it gives us the flexibility to create our own or use third-party libraries. Let's start with creating our own basic form validation.

Building a Basic Form in React

Before we jump into validation, let's build a simple form. Our form will have two fields: an email field and a password field.

import React from 'react';

class App extends React.Component {
  render() {
    return (
      <form>
        <label>
          Email:
          <input type="text" name="email" />
        </label>
        <label>
          Password:
          <input type="password" name="password" />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default App;

Adding a Basic Validation

Let's add some basic validation to our form. We'll start by adding a simple check to see if the email field is empty.

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      errorMessage: ''
    };
  }

  handleInputChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  handleSubmit = (event) => {
    event.preventDefault();
    if (!this.state.email) {
      this.setState({errorMessage: 'Email is required'});
    } else {
      this.setState({errorMessage: ''});
      // Handle form submission here
    }
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Email:
          <input type="text" name="email" onChange={this.handleInputChange} />
        </label>
        <label>
          Password:
          <input type="password" name="password" onChange={this.handleInputChange} />
        </label>
        {this.state.errorMessage && <div>{this.state.errorMessage}</div>}
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default App;

In the code above, we added a handleInputChange function to update our state every time the user types into a field. We also added a handleSubmit function that checks if the email field is empty. If it is, we update our errorMessage state, which is then displayed to the user.

Delving Deeper into Validation

There are many other checks you might want to perform. For instance, you might want to check if the email is in a valid format, or if the password is of a certain length or contains certain characters.

Let's add these checks:

handleSubmit = (event) => {
  event.preventDefault();
  const emailPattern = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/;
  if (!this.state.email) {
    this.setState({errorMessage: 'Email is required'});
  } else if (!emailPattern.test(this.state.email)) {
    this.setState({errorMessage: 'Email is not valid'});
  } else if (this.state.password.length < 8) {
    this.setState({errorMessage: 'Password should be at least 8 characters long'});
  } else {
    this.setState({errorMessage: ''});
    // Handle form submission here
  }
}

The emailPattern is a regular expression (regex) that checks if the email is in a valid format. The test function is a regex function that tests if a string matches a pattern. Think of it as a bouncer checking if the ID matches the person.

Conclusion

Form validation might look like a small task, but it's a crucial part of any application. It's like the goalkeeper in a soccer game. The goalkeeper might have less running around to do compared to other players, but their role is crucial in preventing the opposite team from scoring.

Remember, form validation in ReactJS doesn't need to be complicated. Start with the basics, then gradually add more checks as needed. Just like learning a new language, it might seem overwhelming at first, but with practice, it will become second nature.

ReactJS provides the flexibility and control to handle form validation in a way that suits your application's specific needs. Whether you decide to write your own validation logic or use a third-party library, the important thing is to ensure that your application is secure and provides a good user experience.