// Tutorial //

Red Hot Form Validation for React Using calidation

Published on July 23, 2018
Default avatar
By joshtronic
Developer and author at DigitalOcean.
Red Hot Form Validation for React Using calidation

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking 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:

  1. npm add calidation --save
  1. 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.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!