DEV Community

Cover image for How to Validate Forms Data in React Using Reactrix
Yasser Ameur el idrissi
Yasser Ameur el idrissi

Posted on • Updated on

How to Validate Forms Data in React Using Reactrix

Hello! One of the most common tasks in software development is input validation. Any app has different forms that submit some data, and we want to check numerous conditions: that fields are not empty and that they have a proper format (like emails), length, and so on. Yes, we can do it manually, but this is not the best path. It is better to use a specific validation library. For React apps, the best choice is Reactrix. In this post, we will see how to install it to your Reat apps, how to use it, and observe the most important built-in validators.

Thanks to React's reactivity model, it's really easy to roll your own form validations. This can be done with a simple method call on the form submit.
Thankfully, there are great validation library for React. In this article, we'll be looking at how Reactrix can be used to simplify:

  • Validation
  • Multi-step form validation
  • Child component validation
  • Error messages

We will be using create-react-app for making a React application. Letโ€™s just create a new React app using:

$ npm install -g create-react-app
$ create-react-app form-validation-react
Enter fullscreen mode Exit fullscreen mode

Run the app

$ npm install -g create-react-app
$ create-react-app form-validation-react
Enter fullscreen mode Exit fullscreen mode

This will open our newly created app on http://localhost:3000/

Let have a simple example. Youโ€™re building a signup form. You want to check that user provides a correct input, like:

  • Email has a valid format.
  • All fields are filled.
  • etc

You can do this manually, but it is not the best route to follow. First, is that you will find yourself in a forest of nested if-else constructs, that you most probably could not understand after a week or two. Next, even small additions will bring a lot of changes. This is always safer to rely on an external validation library. For React applications, there are several choices, but in this article we use Reactrix.

You can install Reactrix using your package manager CLI :

npm install reactrix --save
Enter fullscreen mode Exit fullscreen mode

Then, you need to import Reactrix in your src/Login.js components. So Let's define some validations in React components

import React, { useState } from 'react';
import { useValidate } from 'reactrix';

function Login(props) {
  const [data, setData] = useState({});
  const [msg, setValidator] = useValidate();

  const handleChange = (event) => {
    setData({
      ...data,
      [event.target.name]: event.target.value
    );
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    setValidator(data, {
      email: 'required|email',
      password: 'required|string'
    }); 

  }

  return (
    <form>  
        <div className="container">   
          <label>Email : </label>   
          <input type="email" placeholder="Enter Email" name="email" onChange={handleChange} />  
          <label>Password : </label>   
          <input type="password" placeholder="Enter Password" name="password" onChange={handleChange} />  
          <button type="submit" onClick={handleSubmit}>Login</button>     
          Forgot <a href="#"> password? </a>   
        </div>
    </form>
  );

}
Enter fullscreen mode Exit fullscreen mode

Reactrix has built-in localization support for validation messages. The default language for Reactrix is en in order to set the locale you pass the locale key/code to the localize method:

const [msg, setValidator] = useValidate('fr');
Enter fullscreen mode Exit fullscreen mode

You can learn more about Reactrix rules in the Reatrix Repository

๐Ÿ‘‹ Happy Coding.

Top comments (3)

Collapse
 
manishfoodtechs profile image
manish srivastava

Hey Yasser nice article. I am using both serverside as well as clientside validation. Clientside validation is not enough as security . Clientside followed by serverside.

Collapse
 
srezas profile image
SeyedReza SeyedMohseni

but for a high level of security, you should use the database side validation as well ๐Ÿ˜‰

Collapse
 
srezas profile image
SeyedReza SeyedMohseni • Edited

Thanks for sharing that. Can you tell us why this is the best library for validating forms? I've seen some other libraries for this purpose too, like:
github.com/icebob/fastest-validator