闲话不多说,在ruby on rails国度里,对数据的验证非常方便,而且还提供了自定义验证的方法。
Helpers:
1、acceptence
接受协议验证,在很多网站上注册之前都会有一个接受该网站协议的验证,只有你选择yes,才能够继续下去。
class Person < ActiveRecord::Base
validates :terms_of_service, acceptance: true
end
2、validates_associted
关联模型验证,很多modle会和其他model有关联,那么就需要验证关联的model的合法性,但是切忌不要在关联双方都加上该验证,不然会出现递归似循环。
class Library < ActiveRecord::Base
has_many :books
validates_associated :books
end
3、confirmation
确定性验证,有一些属性,比如密码,Email地址等,都需要用户再次输入,页面上会多一个name_confirmation的域,验证时,会同name域进行比较。
class Person < ActiveRecord::Base
validates :email, confirmation: true
validates :email_confirmation, presence: true
end
4、exclusion
验证某个属性不在某个集合中,如果在,则验证失败。
class Account < ActiveRecord::Base
validates :subdomain, exclusion: { in: %w(www us ca jp),
message: "Subdomain %{value} is reserved." }
end
5、format
验证某个属性值是否满足给定的正则表达式。
class Product < ActiveRecord::Base
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
message: "Only letters allowed" }
end
6、inclusion
验证某个属性在某个集合内
class Coffee < ActiveRecord::Base
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end
7、length
验证某个属性长度满足某个值,可以是一个单独的值,也可以是一个长度范围,或者设定最小值,最大值等。
class Person < ActiveRecord::Base
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }
end
8、numericality
验证某个属性必须为数字类型的值(包括Integer,Float等),当需要某个属性只能为整数时,可以添加参数only_integer:true
class Player < ActiveRecord::Base
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
end
同时还可以添加以下参数:
:greater_than
:greater_than_or_equal_to
:equal_to
:less_than
:less_than_or_equal_to
:ood
:even
9、presence
非空验证,也是最常见的验证,可以对关联的模型进行验证。
class Person < ActiveRecord::Base
validates :name, :login, :email, presence: true
belongs_to :order
validates :order, presence: true
end
10、uniqueness
唯一性验证,一般用于昵称,ID,用户名等。
class Person < ActiveRecord::Base
validates :name, uniqueness: { case_sensitive: false }
end
11、validates_with
通过一个继承Validator的类来验证属性
class Person < ActiveRecord::Base
validates_with GoodnessValidator, fields: [:first_name, :last_name]
end
class GoodnessValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] << "This person is evil"
end
end
end