Validatable Delegate

Using the Validatable delegate for object validation

The Validatable@cbValidation delegate (ColdBox 7+) allows you to add validation capabilities directly to any object using ColdBox's delegation pattern. This provides a cleaner, more object-oriented approach to validation.

Overview

Instead of injecting the ValidationManager into every class, you can delegate validation methods directly to your objects. This is available in ColdBox 7 and later.

Basic Setup

Shorthand Syntax

The simplest way to make an object validatable:

User.bx
class delegates="Validatable@cbValidation" {

    property name="id" type="numeric";
    property name="name" type="string";
    property name="email" type="string";

    this.constraints = {
        name: { required: true, size: "2..100" },
        email: { required: true, type: "email" }
    };
}

Selective Method Delegation

Delegate only specific validation methods:

Long Syntax with Property Injection

For more control, use explicit property delegation:

Available Delegated Methods

When using the Validatable delegate, the following methods are available:

  • validate() - Validate and return result object

  • validateOrFail() - Validate or throw exception

  • isValid() - Quick boolean check (stores results)

  • getValidationResults() - Get stored validation results

  • validateHasValue() - Check if a value exists

  • validateIsNullOrEmpty() - Check if value is null/empty

  • assert() - Assert a condition is true

  • getValidationManager() - Access the ValidationManager

Using Delegated Validation Methods

Validate Method

ValidateOrFail Method

For API endpoints with exception handling:

IsValid Method

Quick validation with stored results:

Advanced Usage

Validation with Profiles

Pass profiles for targeted validation:

Custom Validation with Callbacks

Combine validation with business logic:

Best Practices

1. Use Shorthand for Full Delegation

For simple validation needs, use the shorthand syntax:

2. Use Selective Delegation for Lightweight Objects

For objects that only need specific methods:

3. Always Define Constraints

Ensure your object has constraints defined:

4. Use isValid() for Simple Checks

For quick validation without error details:

5. Use validateOrFail() for APIs

For REST endpoints where you need exception handling:

6. Combine with Custom Methods

Add custom validation logic to your objects:

Supported ColdBox Versions

The Validatable delegate requires:

  • ColdBox 7.0+

  • cbValidation 4.1.0+

For earlier ColdBox versions, use the mixin methods via validate() and validateOrFail().

See Also

Last updated

Was this helpful?