validates_acceptance_of
# checkbox 提交後的設置的默認值
class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service, :accept => 'yes'
end
validates_associated
# 關聯驗證
# 驗證當前的model時,也要驗證相關聯的model
class Library < ActiveRecord::Base
has_many :books
validates_associated :books
end
# 不要對進行雙向關聯驗證,這樣會進行死循環的(infinite loop.)
validates_confirmation_of
# 重複性驗證
# 用於驗證密碼,郵件
# 重複驗證的元素必須以"_confirmation"結尾
class Person < ActiveRecord::Base
validates_confirmation_of :email
end
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
# 修改後,重複驗證的元素不能爲空
class Person < ActiveRecord::Base
validates_confirmation_of :email
validates_presence_of :email_confirmation
end
validates_exclusion_of
# 驗證的屬性是否不包含在給定集中
class Account < ActiveRecord::Base
validates_exclusion_of :subdomain, :in => %w(www),
:message => "Subdomain %{value} is reserved."
end
:in 用來預設的驗證集合
validates_format_of
# 驗證格式
class Product < ActiveRecord::Base
validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,
:message => "Only letters allowed"
end
:with 有來設置格式
validates_inclusion_of
# 驗證的屬性是否包含在給定集中
class Coffee < ActiveRecord::Base
validates_inclusion_of :size, :in => %w(small medium large),
:message => "%{value} is not a valid size"
end
:in 用來預設的驗證集合
validates_length_of
# 驗證的屬性長度
class Person < ActiveRecord::Base
validates_length_of :name, :minimum => 2
validates_length_of :bio, :maximum => 500
validates_length_of :password, :in => 6..20
validates_length_of :registration_number, :is => 6
end
:minimum # 設置屬性最小長度
:maximum # 設置屬性最大長度
:in # 指定一個區間
:is # 必須指定一個值
:wrong_length # 長度發生錯誤時,顯示的信息
:too_long # 長度超出時,顯示的信息
:too_short # 長度不足時,顯示的信息
validates_numericality_of
# 指定數字驗證
class Player < ActiveRecord::Base
validates_numericality_of :points
validates_numericality_of :games_played, :only_integer => true
end
:only_integer # 必須爲整數
:greater_than # >
:greater_than_or_equal_to # >=
:equal_to # =
:less_than # <
:less_than_or_equal_to # <=
:odd # 奇數
:even # 偶數
validates_presence_of
# 判空操作
class Person < ActiveRecord::Base
validates_presence_of :name, :login, :email
end
validates_uniqueness_of
# 唯一性驗證
class Account < ActiveRecord::Base
validates_uniqueness_of :email
end
validates_with
# 使用驗證類來進行驗證
class Person < ActiveRecord::Base
validates_with GoodnessValidator
end
class GoodnessValidator < ActiveRecord::Validator
def validate
if record.first_name == "Evil"
record.errors[:base] << "This person is evil"
end
end
end
當發生錯誤信息時,沒有缺省的錯誤信息,需要向error添加錯誤信息
validator類有兩個缺省的參數
record # 被驗證的類
options # 額外的選項
validates_each
# 使用block對多個值進行驗證
Ref:
http://guides.rubyonrails.org/active_record_validations_callbacks.html