rails validation code example

Example 1: rails validators

validates :name, length: { minimum: 2 } # or { maximum: 500 } or { in: 6..20 } or { is: 6 } 
validates :name, :login, :email, presence: true
validates :email, uniqueness: true
validates :switch, inclusion: { in: [true, false]  }
validates :terms_of_service, acceptance: true
validates :size, inclusion: { in: %w(small medium large), message: "%{value} is not a valid size" }
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" }

Example 2: validates inclusion of rails

validates_inclusion_of :size, :in => ['small', 'medium', 'large']

Example 3: active record validates

class Person < ApplicationRecord
  validates :name, :login, :email, presence: true
end

Example 4: active record validates

class Person < ApplicationRecord
  validates :name, presence: true
end

Tags:

Misc Example