This article is about fixing Trigger validation on both onChange and onBlur in Final Form React Final Form
  • 12-Feb-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing Trigger validation on both onChange and onBlur in Final Form React Final Form

Trigger validation on both onChange and onBlur in Final Form React Final Form

Lightrun Team
Lightrun Team
12-Feb-2023

Explanation of the problem

The current behavior of the form library is that validation only occurs based on the value of a boolean configuration option. If the option is set to true, validation happens on the blur event. If the option is set to false, validation occurs on the change event. By default, the option is set to false.

The proposed behavior is to add another configuration option that allows validation to occur on both the change and blur events. This would be achieved by adding two new boolean configuration options: validateOnChange and validateOnBlur.

The requestor of this feature has previously attempted to create their own form library, but found that it is difficult to properly implement performant form libraries in React. They liked the ability to perform synchronous validation on change and asynchronous validation (such as network requests) on blur in their own solution. However, they have not yet found a way to achieve this using existing form libraries.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for Trigger validation on both onChange and onBlur in Final Form React Final Form

To trigger validation on both onChange and onBlur events in Final Form React Final Form, you need to make use of the validate property. This property takes a validation function that is called every time the form state changes, including when either the change or blur event occurs.

Here is an example of how to modify the default behavior of Final Form to validate on both onChange and onBlur events:

import { useState } from 'react';
import { useForm } from 'react-final-form';

const MyForm = () => {
  const [validateOnBlur, setValidateOnBlur] = useState(false);
  const { form } = useForm();

  const handleBlur = () => {
    setValidateOnBlur(true);
  };

  const handleChange = () => {
    setValidateOnBlur(false);
    form.validate();
  };

  return (
    <form onBlur={handleBlur} onChange={handleChange}>
      <Field name="field1" validate={validateOnBlur ? validateField1 : undefined} />
      <Field name="field2" validate={validateOnBlur ? validateField2 : undefined} />
      ...
    </form>
  );
};

In this example, the state validateOnBlur is used to track whether the form is currently in a blur state or a change state. The handleBlur function sets validateOnBlur to true, while the handleChange function sets validateOnBlur to false and immediately calls the form.validate() method.

In the Field components, the validate property is set to either validateField1 or validateField2 based on the value of validateOnBlur. When validateOnBlur is true, the fields will be validated on blur. When validateOnBlur is false, the fields will be validated on change.

Note: validateField1 and validateField2 are the validation functions for each respective field.

Other popular problems with Final Form React Final Form

Problem: Validation on submit only

One common issue with Final Form React Final Form is that by default, validation only occurs when the form is submitted. This can lead to a poor user experience as errors are not displayed to the user until they attempt to submit the form.

Solution:

To resolve this issue, you can modify the default behavior of Final Form to validate on both onChange and onBlur events. You can do this by making use of the validate property, which takes a validation function that is called every time the form state changes, including when either the change or blur event occurs.

Problem: Performance with large forms

Another issue with Final Form React Final Form is that performance can become a concern when working with large forms. This is because Final Form re-renders the entire form on every change, which can be slow if there are many fields.

Solution:

To improve performance with large forms, you can make use of the subscription property in Final Form. This property allows you to specify which parts of the form state you want to subscribe to, so that only the necessary parts of the form are re-rendered. For example, you can subscribe only to changes in fields that are currently being edited, rather than re-rendering the entire form.

Problem: Inconsistent validation behavior

A third issue with Final Form React Final Form is that validation behavior can be inconsistent across different fields in the form. This can lead to confusion for users and can make it difficult to implement complex validation logic.

Solution:

To resolve this issue, you can use the validate property in Final Form to specify a custom validation function for each field. This function can be written to implement the specific validation logic required for each field, ensuring consistent behavior across the entire form. Additionally, you can use the validateFields utility provided by Final Form to programmatically trigger validation for specific fields.

A brief introduction to Final Form React Final Form

Final Form React Final Form is a library for managing form state and validation in React applications. It is designed to make it easy to build forms that are both user-friendly and performant, with a focus on flexibility and ease of use. Final Form React Final Form uses the concept of “controlled components,” which means that form state is stored in a single, centralized location, making it easier to manage form state and ensure consistent behavior across fields.

Final Form React Final Form provides a range of features that make it easy to implement complex validation logic and improve the user experience of forms. For example, it supports both synchronous and asynchronous validation, making it easy to validate form data both locally and by making network requests. Additionally, it provides a simple and flexible API for customizing form behavior, including the ability to subscribe to specific parts of the form state for improved performance with large forms. With these features, Final Form React Final Form is a powerful tool for building forms in React applications.

Most popular use cases for Final Form React Final Form

  1. Form state management

Final Form React Final Form can be used for managing form state in React applications. This includes storing values for individual fields, tracking the state of the form as a whole (e.g., whether it is currently being submitted), and managing errors that occur during validation. With its centralized form state management, Final Form React Final Form makes it easier to build forms that are both user-friendly and performant.

import { useForm } from "final-form";

const MyForm = () => {
  const { form, handleSubmit } = useForm();
  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
    </form>
  );
};
  1. Validation

Final Form React Final Form can be used for implementing form validation in React applications. This includes both synchronous and asynchronous validation, and can be customized using a validation function. With its flexible validation API, Final Form React Final Form makes it easy to implement complex validation logic and ensure that form data is accurate and consistent.

  1. Performance optimization

Final Form React Final Form can be used for optimizing the performance of forms in React applications. This includes the ability to subscribe to specific parts of the form state, so that only the necessary parts of the form are re-rendered. This can be especially important for large forms, where re-rendering the entire form on every change can be slow. With its performance optimization features, Final Form React Final Form makes it easy to build fast, responsive forms that deliver a great user experience.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.