Skip to content

Passing Context to Decorators

Overview

It's possible to pass a custom object to decorators which will be accessible on the ValidationError instance of the property if validation failed.

Example

import { validate } from 'class-validator';

class MyClass {
    @MinLength(32, {
        message: 'EIC code must be at least 32 characters',
        context: {
            errorCode: 1003,
            developerNote: 'The validated string must contain 32 or more characters.',
        },
    })
    eicCode: string;
}

const model = new MyClass();

validate(model).then(errors => {
    // errors[0].contexts['minLength'].errorCode === 1003
});

Use Cases

  • Adding error codes for API responses
  • Including developer notes in validation errors
  • Providing additional metadata for error handling
  • Customizing error messages based on context

Need documentation like this for your own product?

This site was built by Sonicar Tech LLC — we help SaaS, B2B, Enterprise, FinTech, and AI companies launch professional, docs-as-code documentation 60% faster and cheaper than building an in-house team, with first drafts delivered in 1 week.

Visit sonicar.tech