Course contentsShow
← JavaScript
Lesson 664 of 2,72316. Object Methods and PatternsFree lesson

Using Setters for Validation

Implement validation logic in setters to ensure only valid values are assigned to object properties.

Using Setters for Validation

What you'll learn: How to use setter methods to validate data before it's assigned to an object property, ensuring your objects only hold valid values.

Why Validate in Setters?

Setters give you a perfect checkpoint to inspect and approve incoming values before they're stored. Think of a setter as a security guard at a door—it checks credentials before letting anyone in. Without validation, your object might end up with nonsensical data like negative ages or empty names.

How It Works

Inside your setter method, you write conditional logic to test the incoming value. If it passes your rules, you store it in a private property (often prefixed with _). If it fails, you can either ignore it, throw an error, or set a default value.

const user = {
  _age: 0,
  
  set age(value) {
    if (value < 0 || value > 120) {
      console.log('Invalid age');
      return; // Don't store invalid value
    }
    this._age = value;
  },
  
  get age() {
    return this._age;
  }
};

user.age = 25;   // Stored successfully
user.age = -5;   // "Invalid age" — rejected
user.age = 200;  // "Invalid age" — rejected

Common Validation Patterns

You can check for type, range, format, or any custom business rule:

const product = {
  _price: 0,
  
  set price(value) {
    if (typeof value !== 'number' || value < 0) {
      throw new Error('Price must be a positive number');
    }
    this._price = value;
  }
};

Key Takeaway: Setters let you enforce data integrity by validating values before assignment, preventing invalid states and catching bugs at the property level rather than later in your code.