Validations

Reference for CQL model validations.

Validation Macro

validate

Add validation rules to model fields.

validate field_name, rule: value, ...

Validation Rules

presence

Field must not be empty/nil.

validate name, presence: true

Fails when:

  • Value is nil

  • String is empty or whitespace only

  • Array/Hash is empty

length

String length constraints.

Options:

  • min : Int32 - Minimum length

  • max : Int32 - Maximum length

  • is : Int32 - Exact length

format

Match regular expression.

Options:

  • with : Regex - Pattern to match

numericality

Numeric value constraints.

Options:

  • greater_than : Number

  • greater_than_or_equal_to : Number

  • less_than : Number

  • less_than_or_equal_to : Number

  • equal_to : Number

  • other_than : Number

  • odd : Bool

  • even : Bool

inclusion

Value must be in set.

Options:

  • in : Array - Allowed values

exclusion

Value must not be in set.

Options:

  • in : Array - Forbidden values

uniqueness

Value must be unique in database.

Options:

  • scope : Symbol | Array(Symbol) - Columns to scope uniqueness

  • case_sensitive : Bool - Case-sensitive comparison (default: true)

acceptance

Boolean field must be true.

confirmation

Field must match confirmation field.

Validation Options

allow_nil

Skip validation if value is nil.

allow_blank

Skip validation if value is blank.

on

Run validation only in specific context.

Values:

  • :create - Only on create

  • :update - Only on update

  • :save - On create and update (default)

if / unless

Conditional validation.

message

Custom error message.

Custom Validation

validate method

Override for custom logic.

errors.add

Add custom error.

Checking Validity

valid?

Returns true if all validations pass.

invalid?

Returns true if any validation fails.

errors

Access validation errors.

Validation Lifecycle

  1. before_validation callback

  2. Run validations

  3. after_validation callback

  4. If valid, proceed with save

  5. If invalid, abort operation

Complete Example

See Also

Last updated

Was this helpful?