Validate Requests

This guide shows you how to add validation to your request contracts.

Basic Validation

Add the validate macro to your request struct:

struct CreateUserRequest
  include Azu::Request

  getter name : String
  getter email : String
  getter age : Int32?

  def initialize(@name = "", @email = "", @age = nil)
  end

  validate name, presence: true
  validate email, presence: true
end

Validation Rules

Presence

Ensure a field is not empty:

Length

Validate string length:

Format

Validate against a regular expression:

Numericality

Validate numeric values:

Inclusion

Validate value is in a set:

Exclusion

Validate value is not in a set:

Combining Validations

Apply multiple rules to one field:

Custom Validation

Add custom validation logic:

Conditional Validation

Validate based on conditions:

Using Validated Requests in Endpoints

See Also

Last updated

Was this helpful?