Simple form validation client side — Reactjs

timo
4 min readMar 8, 2021

Data validation is the process of ensuring that user input is clean, correct, and useful.

Let’s first create the react application:

npx create-react-app form-validation
cd form-validation
npm start

Create and style the form

Let’s create a registration form with these input fields: name, lastname, email, password and repeat password:

Now we will add some styling to the Form:

We create Form.css file to add all the styles:

Import Form.css at Form.js:

The final look 😎

Handlers

To capture the changes on each input field we will use the onChange event handler and onSubmit handler for the form submission.

Input handler

As mentioned to capture the changes on each input field we will use the onChange event handler. With the value captured by onChange we will update the state. We will pass handleChange function to the onChange event handler.

The onChange returns a Synthetic Event object that holds information of the element it is called by like value, name, id, etc. We need to get the value from the event so that we can update the state every time the user types.

We will use the useState hook to save the values of the inputs on the state. We will use the same handler for all inputs as we will use the name of each input to save them on state. Value is an object and the properties are name, lastname, email, password and repeatPassword:

Form submit handler

Let’s add the onSubmit event to the <form>:

Alert

Let’s declare errors and success state variables. Errors will be an object that will hold the error messages for each field and success will be a boolean value.

const [errors, setError] = React.useState({});  
const [success, setSuccess] = React.useState(false);

Before continuing with the validation let’s first create an Alert component that we will use to display the error and success messages. Alert.js will take two properties type that can be success or error and message that will be the text of the message. Type property it is used to decide the color of the alert.

Let’s start with the validation

We will create validateForm() function to validate all the fileds. This function will return and object with all the errors. The errors returned by this function will be saved on errors state variable by using the setError function.

The validations that we will make for each filed are:

  1. Name is required and at least 2 characters long
  2. Lastname is required and at least 2 characters long
  3. Email is required and must be a valid email
  4. Password is required and must contain at least one number, one uppercase letter, one lowercase letter and at least 8 characters long
  5. Repeat password is required and must be the same as password

For the email and password are used these Regular Expressions:

Email:

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/g

Password:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm

We will call validateForm() at the handleSubmit. If the errors object is empty we can successfully submit the form and show the success message by using SetSuccess(true).

Now let’s add the alerts at each input. The alert is shown only if the specific input has any error:

Since all the fields are required if we leave all of them empty and submit the form, all the error messages must be shown:

If you want to remove the error message when you start typing and not when submitting the form again, you can delete the error for the input that you are writing on. At the onChangeHandler delete the property with the name of the field you are typing on:

const handleChange = (event) => {setValue({ ...value, [event.target.name]: event.target.value });let allErrors = errors;delete allErrors[event.target.name];setError(allErrors);event.preventDefault();};

Success

--

--

timo

I am curious and amazed by the new technologies and how they affect our life and business.