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
| Parameter | Type | Description |
|---|---|---|
issues | Issue[] | 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 }tovalidateorparse.
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
- validate — the
errorsfield with the first error of each field - ValidationError