Categories
React

Make Form Handling Easy in React Apps with Formik— Field Level Validation

Spread the love

Formik is a library that makes form handling in React apps easy.

In this article, we’ll look at how to handle form inputs with Formik.

Field Level Validation

We can add field-level validation by creating validation functions and passing it into the validate prop of the Field component.

For instance, we can write:

import React from "react";
import { Formik, Form, Field } from "formik";

function validateEmail(value) {
  let error;
  if (!value) {
    error = "Required";
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(value)) {
    error = "Invalid email address";
  }
  return error;
}

export const FormExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        email: ""
      }}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched, isValidating }) => (
        <Form>
          <Field name="email" validate={validateEmail} />
          {errors.email && touched.email && <div>{errors.email}</div>}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We create the validateEmail function that takes the value parameter, which has the input value.

Then we check the value and return validation error messages after we checked if the value is valid.

In FormExample , we create the form with the Formik and Form components.

initialValues has the initial value of each field.

The Field component has the name prop set to the same value as in the initialValues .

validate has the validation function we created earlier.

errors has the error message.

touched has the touched state of the input.

isValidating tells us whether the form is being validated.

Manually Triggering Validation

We can manually trigger validation with Formik.

For instance, we can write:

import React from "react";
import { Formik, Form, Field } from "formik";
function validateUsername(value) {
  let error;
  if (value === "admin") {
    error = "Nice try!";
  }
  return error;
}

export const FormExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        username: "",
      }}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched, validateField, validateForm }) => (
        <Form>
          <Field name="username" validate={validateUsername} />
          {errors.username && touched.username && <div>{errors.username}</div>}
          <button type="button" onClick={() => validateField("username")}>
            Check Username
          </button>
          <button
            type="button"
            onClick={async () => {
              const result = await validateForm();
              console.log(result);
            }}
          >
            Validate All
          </button>
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We have the validateUsername function that validates the username field.

In the Form element, we have the Check Username button that calls validateField with 'username' , which is the name value of the Field component.

The names will be matched so validateUsername function will be run.

We can validate all the fields in the form with the validateForm function, which returns a promise with any errors that are found.

So if we type in ‘admin’ into the input, the returned promise will resolve to:

{username: "Nice try!"}

Conclusion

We can add field level validation and manually trigger form validation with Formik.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *