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