Skip to content

flatten ​

Collects all error messages by field — in Laravel format: { email: ['...', '...'] }. Handy for API responses when the frontend already shows Laravel errors.

Signature ​

ts
function flatten(issues: Issue[]): Record<string, string[]>

Parameters ​

ParameterTypeDescription
issuesIssue[]result.issues from validate or error.issues from ValidationError

Notes ​

  • The key is a dot path, as in errors: address.city, items.0.title. An error of the value itself is under ''.
  • By default there is one error per field. To get all of them, pass { all: true } to validate or parse.

Example ​

ts
import { parse, flatten, ValidationError } from 'tinyval';

app.post('/users', (req, res) => {
  try {
    const user = parse(CreateUser, req.body, { all: true });
  } catch (e) {
    if (e instanceof ValidationError) {
      return res.status(422).json({ message: 'The given data was invalid.', errors: flatten(e.issues) });
      // { "errors": { "password": ["Must be at least 8 characters long", "Invalid format"] } }
    }
    throw e;
  }
});

See also ​