question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Post validate values processing before onSubmit call

See original GitHub issue

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

I use yup validation together with this library. I implemented a simple helper:

import yup from 'yup';
import { setIn } from 'final-form';

const validate = async (values, schema) => {
  if (typeof schema === 'function') {
    schema = schema();
  }

  try {
    await schema.validate(values, { abortEarly: false });
  } catch (e) {
    return e.inner.reduce((errors, error) => {
      return setIn(errors, error.path, error.message);
    }, {});
  }
};

which I can use like this:

import React from 'react';
import yup from 'yup';
import { Form, Field } from 'react-final-form';

const schema = yup.object({
  name: yup.string().required(),
  surname: yup.string().required(),
});

const UserForm = ({ onSubmit }) => (
  <Form
    onSubmit={onSubmit}
    validate={values => validate(values, schema)}
    render={({ handleSubmit, values }) => (
      <form onSubmit={handleSubmit} autoComplete="off">
        <Field name="name" placeholder="name" component="input" />
        <Field name="surname" placeholder="surname" component="input" />
        <button type="submit" >Submit</Button>
      </form>
    )}
  />
);

What is the expected behavior?

Currently, Form validate prop is used only to validate, but there is no way to change form values here, I can only return errors or nothing, when I return nothing, form values which were validated will go to onSubmit handler. It would be great to allow values postprocessing in validate step.

One use case - very popular yup library has casting abilities before validation, for example yup.number() will try to convert '1' to 1 before validation. I need this because I have a really complex form, in which many fields are conditionally based on type field. For instance, type a has x and y fields, type b has z field. Now, if a user goes back and forth between type a and b and he fills them, my values object will contain x, y and z keys, but in onSubmit with type b, I want values to have only z key. Now, whats nice about yup, its validate method returns casted object, with optional removing unnecessary attrs as well. Here are the options I see:

  1. I could use yup again in onSubmit - highly inefficient as all validation logic would be triggered again
  2. Maybe I could pass FormApi to validate myself to my validate helper, and then I could update values there.
  3. We could add FormApi to Form validate prop next to values, then it would be already available
  4. This option is hardcore (breaking change), but the cleanest in my opinion would be to change how validate prop works. Currently, validate return errors or undefined or a corresponding Promise. We could change it to throw an error or return a rejected promise in case of a submit error, or a values object in case user input was valid - we could return casted values here if we wanted. So I could refactor validate like this:
import yup from 'yup';
import { setIn } from 'final-form';

const validate = async (values, schema) => {
  if (typeof schema === 'function') {
    schema = schema();
  }

  try {
    const castedValues = await schema.validate(values, { abortEarly: false, stripUnknown: true });
  } catch (e) {
    throw e.inner.reduce((errors, error) => {
      return setIn(errors, error.path, error.message);
    }, {});
  }

  return castedValues;
};
  1. Softer version of above, implementing a new prop like preSubmit, which would exist next to validate, so it woudn’t be a breaking change anymore

What’s your environment?

react-final-form: 3.0.2, final-form: 4.0.0

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:2
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
Noitidartcommented, Nov 20, 2018

Great topic though, thanks for posting. As it gives me idea on how to use yup. I wanted to use yup.

1reaction
piehouseratcommented, Nov 28, 2018

@Noitidart Yup (no pun intended) me too, would be good to add a Yup example to the docs

Read more comments on GitHub >

github_iconTop Results From Across the Web

Form data validation before submission - Stack Overflow
Whenever i click on submit button, it asks for validation but without validating it is submitted to database. I want onsubmit, it asks...
Read more >
Form Validation | validate form input before submitting the data
Here we'll learn the methods used to validate form input, using the onSubmit event handler. Page Navigation: Validating Form Input · Implementing the...
Read more >
React Forms Tutorial: Access Input Values, Validate, Submit ...
A step by step tutorial on how to access input values, validate, and submit forms in React.
Read more >
How onsubmit Event work in JavaScript? Examples - eduCBA
The JavaScript onsubmit is one of the event handling function used for performing the operations in web based applications. It is used to...
Read more >
useForm | React Hook Form - Simple React forms validation
This option allows you to configure the validation strategy before a user submits the form that is happened during onSubmit event by invoking...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Hashnode Post

No results found