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
endAvailable 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 emptyrequired: true: Ensures the field is not nil
Numeric Comparisons
gt: value: Greater thangte: value: Greater than or equal tolt: value: Less thanlte: value: Less than or equal toeq: value: Equal to
Size Validations
size: number: Exact sizesize: range: Size within range
Pattern Matching
match: regex: Must match regular expression
Inclusion and Exclusion
in: array: Value must be in the arrayin: range: Value must be in the rangeexclude: array: Value must not be in the arrayexclude: 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
Related Features
Active Record Models - How to define models with validations
Callbacks - Lifecycle hooks that work with validations
CRUD Operations - How validations integrate with save operations
Error Handling - Working with validation errors
Last updated
Was this helpful?