Written by: Geoffrey Callaghan

Formsy React Tutorial

Formsy React Tutorial

Formsy React is a powerful form library for React that simplifies form validation and handling. It allows you to create forms with complex validation rules and manage form state efficiently. This tutorial will guide you through the basics of setting up and using Formsy React.

Step 1: Setup Your React Project

If you don’t already have a React project, you can create one using Create React App:

npx create-react-app my-formsy-app
cd my-formsy-app

Step 2: Install Formsy React

Install Formsy React using npm or yarn:

npm install formsy-react
# or
yarn add formsy-react

Step 3: Basic Usage

Here’s a simple example to demonstrate how to use Formsy React to create a form with validation.

  1. Import Formsy Components:

First, import the necessary components from Formsy React:

import React from 'react';
import Formsy from 'formsy-react';
import { FormsyText, FormsyCheckbox } from '@formsy/material-ui'; // If using Material-UI components
  1. Create a Basic Form Component:

Next, create a form component and define the form fields and validation rules:

const MyForm = () => {
  const [canSubmit, setCanSubmit] = React.useState(false);

  const enableButton = () => {
    setCanSubmit(true);
  };

  const disableButton = () => {
    setCanSubmit(false);
  };

  const submit = (model) => {
    console.log(model);
  };

  return (
    <Formsy
      onValidSubmit={submit}
      onValid={enableButton}
      onInvalid={disableButton}
    >
      <div>
        <label htmlFor="name">Name</label>
        <FormsyText
          name="name"
          validations="isAlpha"
          validationError="Please provide a valid name"
          required
        />
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <FormsyText
          name="email"
          validations="isEmail"
          validationError="Please provide a valid email"
          required
        />
      </div>
      <button type="submit" disabled={!canSubmit}>
        Submit
      </button>
    </Formsy>
  );
};

export default MyForm;

Step 4: Validating Form Fields

Formsy React provides a variety of built-in validation rules. You can also define custom validation rules if needed.

  1. Using Built-in Validation Rules:

Here are a few examples of using built-in validation rules:

<FormsyText
  name="name"
  validations="isAlpha"
  validationError="Please provide a valid name"
  required
/>

<FormsyText
  name="email"
  validations="isEmail"
  validationError="Please provide a valid email"
  required
/>

<FormsyText
  name="age"
  validations="isNumeric,min:18,max:99"
  validationError="Please provide a valid age between 18 and 99"
  required
/>
  1. Creating Custom Validation Rules:

You can create custom validation rules using the validations prop:

<FormsyText
  name="password"
  validations={{
    minLength: 6,
    maxLength: 12,
    customValidation: (values, value) => value && value.match(/[a-z]/) && value.match(/[A-Z]/) && value.match(/[0-9]/)
  }}
  validationErrors={{
    minLength: "Password must be at least 6 characters",
    maxLength: "Password cannot exceed 12 characters",
    customValidation: "Password must include lower, upper case letters and a number"
  }}
  required
/>

Step 5: Handling Form Submission

You can handle form submission using the onValidSubmit prop of the Formsy component:

const submit = (model) => {
  console.log('Form Data:', model);
};

Step 6: Using Formsy with Material-UI

Formsy React can be easily integrated with Material-UI components for a better user interface.

  1. Install Material-UI:
npm install @material-ui/core @formsy/material-ui
# or
yarn add @material-ui/core @formsy/material-ui
  1. Create a Form Using Material-UI Components:
import React from 'react';
import Formsy from 'formsy-react';
import { FormsyText } from '@formsy/material-ui';
import { Button } from '@material-ui/core';

const MyMaterialForm = () => {
  const [canSubmit, setCanSubmit] = React.useState(false);

  const enableButton = () => {
    setCanSubmit(true);
  };

  const disableButton = () => {
    setCanSubmit(false);
  };

  const submit = (model) => {
    console.log(model);
  };

  return (
    <Formsy
      onValidSubmit={submit}
      onValid={enableButton}
      onInvalid={disableButton}
    >
      <FormsyText
        name="name"
        label="Name"
        validations="isAlpha"
        validationError="Please provide a valid name"
        required
      />
      <FormsyText
        name="email"
        label="Email"
        validations="isEmail"
        validationError="Please provide a valid email"
        required
      />
      <Button type="submit" variant="contained" color="primary" disabled={!canSubmit}>
        Submit
      </Button>
    </Formsy>
  );
};

export default MyMaterialForm;

Conclusion

Formsy React is a flexible and powerful library for handling form validation and state management in React applications. This tutorial covered the basics of setting up and using Formsy React, including creating forms, adding validation, and handling form submission. For more advanced usage and detailed documentation, refer to the official Formsy React documentation.