Course contentsShow
← JavaScript
Lesson 2090 of 2,72343. DecoratorsFree lesson

Validation Decorators

Apply decorators to validate method parameters or class field values automatically before execution.

Validation Decorators

You'll learn how to automatically validate method parameters or class fields using decorators before code executes.

What Are Validation Decorators?

Validation decorators act like automated gatekeepers for your class methods and fields. Instead of cluttering your business logic with repetitive type-checks and value validations, you attach a decorator that intercepts and validates input before your actual code runs. If validation fails, the decorator can throw an error immediately—preventing invalid data from corrupting your logic.

Think of it like airport security: passengers (parameters) must pass through checks before boarding the plane (executing the method). The security checkpoint (decorator) operates independently from the airline's operations.

How They Work

A method decorator can wrap the original function, inspect arguments, validate them, and either call the original or throw an error. A field decorator can validate initial values during class instantiation or when values are set.

function validatePositive(value, context) {
  return function(initialValue) {
    if (initialValue <= 0) {
      throw new Error(`${context.name} must be positive`);
    }
    return initialValue;
  };
}

function requireString(target, context) {
  return function(...args) {
    if (typeof args[0] !== 'string') {
      throw new TypeError(`${context.name} expects a string`);
    }
    return target.apply(this, args);
  };
}

class Product {
  @validatePositive
  price = 100;

  @requireString
  setName(name) {
    this.name = name;
  }
}

const item = new Product();
item.setName(123); // TypeError: setName expects a string

Key Benefits

Validation decorators centralize validation logic, making it reusable across multiple classes and methods. Your actual business methods stay clean and focused on their core purpose, while decorators handle cross-cutting concerns like input validation.

Key Takeaway: Validation decorators let you enforce constraints on method parameters and field values declaratively, catching invalid data before it reaches your logic and keeping your code DRY.