🚀 Documentation crafted by Sonicar Tech LLC — get your own docs shipped in 1 week →
Class Validator Documentation by Sonicar.Tech
Validation

Inheriting Validation Decorators

How class-validator decorators are inherited and combined when a subclass extends a base class with its own validators.

When you define a subclass that extends from another class, the subclass will automatically inherit the parent's decorators. If a property is redefined in the descendant class, decorators will be applied from both its own class and the base class.

Example

import { validate } from 'class-validator';

class BaseContent {
    @IsEmail()
    email: string;

    @IsString()
    password: string;
}

class User extends BaseContent {
    @MinLength(10)
    @MaxLength(20)
    name: string;

    @Contains('hello')
    welcome: string;

    @MinLength(20)
    password: string;
}

let user = new User();

user.email = 'invalid email'; // inherited property
user.password = 'too short'; // password will be validated against IsString and MinLength
user.name = 'not valid';
user.welcome = 'helo';

validate(user).then(errors => {
    // handle errors
}); // it will return errors for email, password, name and welcome properties

Inheritance Rules

  • All decorators from the base class are inherited
  • Decorators can be overridden in the child class
  • Multiple decorators are combined when a property is redefined
  • Inheritance works with multiple levels of inheritance

🚀 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, with first drafts delivered in 1 week.

Visit sonicar.tech →

On this page