Search code examples
redux-form

Sync validation to throw form level error (rather then field level)


In sync validation per - https://redux-form.com/7.1.2/examples/syncvalidation/ - I was trying to throw a form level error. Just like when we do throw new SubmissionError({ _error:'form level error from on submit' }), however I am not able to figure it out. I tried using the special _error key and even just error key like so:

reduxForm({
    validate: values => ({ error:'form level??', _error:'form level alt??' })
})

However it is not setting FormProps error value. Does anyone know if this is supported or how to achieve this?


Solution

  • To pass form-level error to form after validation you should add _error property to object returned by redux-form config validate function.

    The error will be passed as error prop to your form component.

    For example:

    import React from 'react';
    import { Field, reduxForm } from 'redux-form';
    
    const ExampleForm = (props) => {
      const { handleSubmit, pristine, submitting, error } = props;
      return (
        <form onSubmit={handleSubmit}>
          <div>
            <label>Name</label>
            <div>
              <Field
                name="name"
                component="input"
                type="text"
                placeholder="Name"
              />
            </div>
          </div>
          <div>Error: {error}</div>
          <div>
            <button type="submit" disabled={pristine || submitting}>Submit</button>
          </div>
        </form>
      );
    };
    
    const validate = (values) => ({
      _error: `form level error for firstName = '${values.name || ''}'!`,
    });
    
    export default reduxForm({
      form: 'exampleForm',
      validate,
    })(ExampleForm);
    

    Edit Redux Form - Simple Example