final-form / react-final-form-arrays

A component for rendering and editing arrays 🏁 React Final Form
MIT License
205 stars 70 forks source link

FieldArray global error #83

Closed VincentCharpentier closed 5 years ago

VincentCharpentier commented 5 years ago

Are you submitting a bug report or a feature request?

feature request

What is the current behavior?

We can perform validation on each value and report errors

What is the expected behavior?

I'd like to have a global validation (on number of entries for eg)

Other information

I tried to initialize my errors object to an empty array, then setting a _error property on it, but that is not working as soon as I have elements in the array it seems.

function validate(values) {
  const errors = [];
  if (!values || values.length < 2) {
    errors._error = 'Min 2 values';
  }
  return errors;
}

// ...

<FieldArray name="myname" validate={validate}>
  {({ fields, meta: { error = {} } }) => {
    const { _error: globalError } = error;
    return (
      <div>
        <div>{globalError}</div>
        {fields.map((name, index) => (
          <Field key={index} name={name} component={TextInput} label={`Value ${index + 1}`} />
        ))}
        <button onClick={() => fields.push('')}>Add a value</button>
      </div>
    );
  }}
</FieldArray>

At first the error will be printed above the button. And when I add a value the error disappear (it should stay until I have at least 2 values).

final-form: "4.13.0"
react-final-form: "4.1.0"
react-final-form-arrays: "2.0.1"
erikras commented 5 years ago

First of all, thanks from migrating from Redux-Form. 😜 The _error was a horrible hack from that library.

For field-level FieldArray validate prop, for an error for the entire array, you just return the string. Errors for the fields inside the array should be handled with validate props on the Fields.

Edit 🏁 React Final Form - Field Arrays

If you need to do record-level validation, there's a special key (you can think of it as replacing the '_error' key) called ARRAY_ERROR that you can import from final-form.

Edit 🏁 React Final Form - Field Arrays

VincentCharpentier commented 5 years ago

Thanks for the help Erik !

That's perfect, just need to check if error is an array before rendering it

Also, really good work; Migrating from redux-form is really easy :+1: