Add Validations

This guide shows you how to add validations to your CQL models to ensure data integrity.

Basic Validation Syntax

Use the validate macro to define validations:

struct User
  include CQL::ActiveRecord::Model(Int64)
  db_context MyDB, :users

  property id : Int64?
  property name : String
  property email : String
  property age : Int32 = 0

  validate :name, presence: true
  validate :email, required: true, match: /@/
  validate :age, gt: 0, lt: 120

  def initialize(@name : String, @email : String, @age : Int32 = 0)
  end
end

Available Validators

Presence and Required

Size

Numeric Comparisons

Pattern Matching

Inclusion and Exclusion

Custom Error Messages

Add the message parameter:

Checking Validity

Check if Valid

Access Errors

Validate and Raise

Custom Validators

For complex validation logic, create a custom validator:

Uniqueness Validation

Check for uniqueness manually in a custom validation:

Validations and Save

Validations run automatically when saving:

Verify It Works

Last updated

Was this helpful?