Tutorial

Red Hot Form Validation for React Using calidation

React

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Validation comes in two varieties. Back end (or server-side) to check that everything sent by the client is good and front end (or client-side) to check on things before anything is sent. While both necessary, client-side validation leads to significantly improved user experience without the overhead of going back and forth with a server.

calidation is a library that aids in client-side form validation by providing a component that you can wrap your forms in. This component accepts a configuration with your validation rules and accepts a function as a child that contains the field values, any errors and whether or not the form is valid.

To get started, add calidation to your project with npm or yarn:

Via npm:

  • npm add calidation --save
  • yarn add calidation

With calidation added to our project, we can put together a simple login form with ease!

import React, { Component, Fragment } from "react";
import { FormValidation } from "calidation";

class LoginForm extends Component {
  onSubmit = ({ fields, errors, isValid }) => {
    if (isValid) {
      // This is where we'd handle our submission...
      // `fields` is an object, { field: value }
      console.log('Everything is good:', fields);
    } else {
      // `errors` is also an object!
      console.log('Something is wrong:', errors);
    }
  };

  render() {
    const config = {
      email: {
        isRequired: "Email field is required!",
        isEmail: "Valid emails only, please!"
      },
      password: {
        isRequired: "Password field required!",
        isMinLength: {
          message: "16+ character password is required",
          length: 16
        }
      }
    };

    return (
      <FormValidation onSubmit={this.onSubmit} config={config}>
        {({ fields, errors, submitted }) => (
          <Fragment>
            <label for="email">Email</label>
            <input
              name="email"
              type="email"
              value={fields.email}
            />
            {submitted && errors.email &&
              <div className="error">{errors.email}</div>
            }
            <label for="password">Password</label>
            <input
              name="password"
              type="password"
              value={fields.password}
            />
            {submitted && errors.password &&
              <div className="error">{errors.password}</div>
            }
            <button>Login</button>
          </Fragment>
        )}
      </FormValidation>
    );
  }
}

export default LoginForm;

The library even takes care of checking the input as it is entered without any additional event handlers written by us.

Coming from the land of validator and debouncing change events for each input, this approach is a breath of fresh air.


The login form example is really just the tip of the iceberg as the calidation library provides so much more than the few validation methods we utilized. It even supports rolling your own validation methods and conditional rules!

Here’s a full list of validation methods you get out of the box:

{
  field: {
    isRequired: 'This field is required',
    isNumber: 'This field must be a number',
    isEqual: {
      message: 'This field must equal 10',
      value: 10,
    },
    isGreaterThan: {
      message: 'This field must be greater than 0',
      value: 0,
    },
    isLessThan: {
      message: 'This field must be less than 20',
      value: 20,
    },
    isEmail: 'This field must be a valid email address',
    isRegexMatch: {
      message: 'This field is alphanumeric',
      regex: /^[a-z0-9]$/,
    },
    isWhitelisted: {
      message: 'Field must be crocodilian',
      whitelist: ['alligator', 'crocodile'],
    },
    isBlacklisted: {
      message: 'Field must NOT be crocodilian',
      blacklist: ['alligator', 'crocodile'],
    },
    isMinLength: {
      message: 'Field must be at least 10 characters',
      length: 10,
    },
    isMaxLength: {
      message: 'Field must be no more than 20 characters',
      length: 10,
    },
    isExactLength: {
      message: 'Field must be exactly 5 characters',
      length: 5,
    },
  }
}

More advanced topics like rolling your own “calidator” and conditional validation logic are very well documented by the library’s author.

And for a live demo of our login component from earlier, you can check out this CodeSandbox.

Creative Commons License