Complete reference for all validation options available in CQL models.
validate :field_name, option: value, option2: value2Validates that a field is not nil and not empty.
validate :name, presence: true
validate :email, presence: trueError: "field_name is required"
Validates that a field matches a regular expression.
validate :email, match: /@/
validate :phone, match: /^\d{10}$/
validate :slug, match: /^[a-z0-9-]+$/Error: "field_name format is invalid"
Validates the length of a string or size of a collection.
validate :password, size: 8..128 # Range
validate :username, size: 3..20
validate :tags, size: 1..5 # Array sizeError: "field_name must be between X and Y characters"
Validates numeric values are within bounds.
validate :age, gte: 0 # Greater than or equal to 0
validate :age, lte: 150 # Less than or equal to 150
validate :quantity, gte: 1, lte: 100 # Between 1 and 100
validate :price, gt: 0 # Greater than 0Error: "field_name must be greater than X" / "field_name must be less than or equal to X"
Validates that a value is in a list of allowed values.
validate :status, in: ["pending", "active", "cancelled"]
validate :role, in: ["admin", "moderator", "user"]
validate :priority, in: [1, 2, 3, 4, 5]Error: "field_name must be one of: X, Y, Z"
Validates that a value is not in a list of excluded values.
validate :username, exclude: ["admin", "root", "system"]
validate :status, exclude: ["deleted"]Error: "field_name must not be included in [X, Y, Z]"
Multiple validations can be applied to a single field:
validate :email, presence: true, match: /@/
validate :username, presence: true, size: 3..20, match: /^[a-z0-9_]+$/
validate :age, presence: true, gte: 0, lte: 150struct User
include CQL::ActiveRecord::Model(Int64)
db_context MyDB, :users
property id : Int64?
property email : String
property username : String
property password : String
property age : Int32?
property role : String = "user"
# Required fields
validate :email, presence: true
validate :username, presence: true
validate :password, presence: true
# Format validations
validate :email, match: /^[^@\s]+@[^@\s]+\.[^@\s]+$/
validate :username, match: /^[a-z0-9_]+$/
# Length validations
validate :username, size: 3..20
validate :password, size: 8..128
# Numeric constraints
validate :age, gte: 0, lte: 150
# Allowed values
validate :role, in: ["admin", "moderator", "user"]
enduser = User.new("test", "test@example.com", "password123")
if user.valid?
user.save
else
user.errors.each do |error|
puts error
end
end
# Or use save! which raises on validation failure
begin
user.save!
rescue CQL::ValidationError => e
puts "Validation failed: #{e.message}"
endFor complex validations, use callbacks:
struct Order
include CQL::ActiveRecord::Model(Int64)
property id : Int64?
property total : Float64
property discount : Float64 = 0.0
before_save :validate_discount
private def validate_discount
if @discount > @total
errors.add(:discount, "cannot exceed total")
return false
end
true
end
end