Active Record Validations Helpers

闲话不多说,在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值