Validations

CQL provides a comprehensive validation system that ensures data integrity before records are saved to the database. The validation system is built on a predicate-based approach that leverages Crystal's type system for compile-time safety.


Basic Validation Syntax

Define validations using the validate macro with field names and validation predicates:

class User
  include CQL::ActiveRecord::Model(Int32)
  db_context UserDB, :users

  property id : Int32?
  property name : String
  property email : String
  property age : Int32 = 0
  property password : String?
  @[DB::Field(ignore: true)]
  property password_confirmation : String?

  # Define validations with predicates and custom messages
  validate :name, presence: true, size: 2..50, message: "Name is invalid"
  validate :email, required: true, match: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, message: "Email format is invalid"
  validate :age, gt: 0, lt: 120, message: "Age must be between a reasonable range"
  validate :password_confirmation, presence: true, message: "Password confirmation is required"

  def initialize(@name : String, @email : String, @age : Int32 = 0, @password : String? = nil, @password_confirmation : String? = nil)
  end
end

Available Validation Predicates

CQL provides a rich set of built-in validation predicates:

Presence and Required

  • presence: true: Ensures the field is not nil and not empty

  • required: true: Ensures the field is not nil

Numeric Comparisons

  • gt: value: Greater than

  • gte: value: Greater than or equal to

  • lt: value: Less than

  • lte: value: Less than or equal to

  • eq: value: Equal to

Size Validations

  • size: number: Exact size

  • size: range: Size within range

Pattern Matching

  • match: regex: Must match regular expression

Inclusion and Exclusion

  • in: array: Value must be in the array

  • in: range: Value must be in the range

  • exclude: array: Value must not be in the array

  • exclude: range: Value must not be in the range


Custom Messages

Provide custom error messages for better user experience:


Working with Validation Errors

Checking if a Record is Valid

Accessing Validation Errors

Validating with Context

You can validate with specific contexts for different scenarios:

Validation Exceptions

Force validation and raise an exception if invalid:


Custom Validators

Create custom validators for complex validation logic:


Validation Best Practices

1. Use Appropriate Predicates

2. Provide Clear Error Messages

3. Use Context-Specific Validations

4. Test Validations Thoroughly


Last updated

Was this helpful?