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

Property Validation on Set

Use field decorators to validate values before they are assigned to class properties.

Property Validation on Set

You'll learn how to use field decorators to automatically validate values whenever they're assigned to class properties.

The Core Idea

Field decorators let you intercept and validate values before they're stored in a property. Instead of scattering validation logic throughout your class methods or relying on developers to remember validation rules, you attach a decorator to the field itself. Every time someone tries to set that property, your validation runs automatically—like a gatekeeper checking credentials before letting someone through.

Think of it like a security checkpoint: the decorator inspects incoming values and either approves them (allows assignment) or rejects them (throws an error), ensuring your class always maintains valid internal state.

How It Works

A field decorator receives a context object that includes access methods. You can override the default set behavior to add validation logic:

function validatePositive(value, context) {
  const originalSet = context.access.set;
  
  context.access.set = function(newValue) {
    if (typeof newValue !== 'number' || newValue <= 0) {
      throw new Error(`${context.name} must be a positive number`);
    }
    originalSet.call(this, newValue);
  };
  
  return value; // Initial value
}

class Product {
  @validatePositive
  price = 0;
  
  @validatePositive
  quantity = 1;
}

const item = new Product();
item.price = 50; // ✓ Works
item.price = -10; // ✗ Throws error

The decorator wraps the setter, performs validation, then calls the original setter if the value passes.

Key Takeaway: Field decorators with custom set logic let you enforce validation rules declaratively, ensuring properties never hold invalid values throughout their lifetime.