0
votes

I have a React-Final-Form that validates its form fields.

I would like to not invoke validation when a cancel or reset button is clicked. However, if clicking the cancel button click causes an invalid field to render its error message, the onCancel function is never called. This happens even if I set the button type to "reset".

If validate doesn't return a change, only then can the onCancel function be reached.

  handleSubmit(values) { console.log(JSON.stringify(values, 0, 2)) }

  onCancel() { console.log("cancelled!"); }

  render() {
    const onSubmit = async values => { this.handleSubmit(values); };

   return (
     <Form name="form" 
        onSubmit={onSubmit}
        validate={values => {
                  const errors = {};
                  if (!values.username) { errors.username = 'Required' }
                  return errors }}

        render={({handleSubmit}) => (
          <form onSubmit={handleSubmit}>
            <Field name="username">
              {({ input, meta }) => (
                 <input {...input} type="text" placeholder="Username" autoFocus>
                 {meta.error && meta.touched && <span>{meta.error}/span>}                   
              )}
            </Field>

            <button type="submit">Submit</button>
            <button type="button" onClick={onCancel}>Cancel</button>
          </form>
        )}/>
  );
1
Bottom line, to answer the question, please specify how to suspend form validation via react-final-form or some other way outside of the final-form framework.Heather92065
It isn't the case in this poster's question, but for those that arrive via Google search: don't forget that a button without a type attribute automatically has a submit type, and will therefore touch all fields and show any errors, regardless of what its onClick function says. To prevent that, add type=button.Chris Chiasson
<button type="submit" onClick={() => form.change("btnClicked", "CANCEL"))}>Cancel</button>, followed by in your validate function => if(values.btnClicked !== "CANCEL") {...do something}. This will allow you to bypass the validation as wellforeverAnIntern

1 Answers

1
votes

The error is being shown because clicking the Cancel button is blurring the field, causing meta.touched to become true. It's not "invoking validation", the error was already calculated.

It doesn't make sense to me that the onCancel is not getting called. It certainly seems to be when I run this code.

Edit stupefied-feistel-6kn9p

If you want Cancel to reset the form, you need to call form.reset(). Like in this example.

If you need the errors to not show and not reset the form, you'll need to manage that state yourself.