TanStackT
TanStack11mo ago
4 replies
primary-violet

Getting all errors from field AND subfield

I have three subfields I would like to have a list of errors from. I noticed that there isn't a convenient way to do that, which either means I have to manually call <form>#getFieldMeta() on all subpaths, or get all errors and reduce them based on my parent field's name.

Is there an easier way?

Example of my implementation:
function allErrorsOfFieldAndSubfield(
  fields: Record<
    string,
    {
      errors: ValidationError[];
    }
  >,
  namespace: string,
) {
  return Object.entries(fields).reduce<ValidationError[]>((errors, [name, field]) => {
    if (!name.startsWith(namespace)) {
      return errors;
    }
    errors.push(...field.errors);
    return errors;
  }, []);
}

// usage
const errors = allErrorsOfFieldAndSubfield(form.getAllErrors().fields, 'parentKey'); 
Was this page helpful?