rails 校验大全(转载)

可以自定义validate(), 这个方法在每次保存数据时都会被调用.
如:

def validate
 if name.blank? && email.blank?
  errors.add_to_base("You must specify a name or an email address")
 end
end

同时也可以自定义 validate_on_create(), validate_on_update()方法.
 valid?()方法可以随时调用,用来测试数据是否能通过校验
返回的错误信息可用 error_messages_for(model)方法显示.
如:<%= error_messages_for 'article' %>

校验大全:
validates_acceptance_of
 指定checkbox应该选中. (如:(*)我同意条款)
 用法:validates_acceptance_of attr... [ options... ]
 参数:message text  默认:“must be accepted.”
   :on :save, :create, or :update
 实例:
 class Order < ActiveRecord::Base
  validates_acceptance_of :terms,
              :message => "Please accept the terms to proceed"
 end

validates_associated
 查验指定的object.
 用法:validates_associated name... [ options... ]
 参数:message text 默认: is “is invalid.”
   :on :save, :create, or :update
 实例:
 class Order < ActiveRecord::Base
  has_many :line_items
  belongs_to :user
  validates_associated :line_items,
            :message => "are messed up"
  validates_associated :user
 end

validates_confirmation_of
 数据重校
 用法:validates_confirmation_of attr... [ options... ]
 参数:message text 默认 “doesn’t match confirmation.”
   :on :save, :create, or :update
 实例:
 对密码表:
 <%= password_field "user", "password" %><br />
 <%= password_field "user", "password_confirmation" %><br />
 #第二表名为xxxx_confirmation
 class User < ActiveRecord::Base
  validates_confirmation_of :password
 end

validates_each
 使用block检验一个或一个以上参数.
 用法:validates_each attr... [ options... ] { |model, attr, value| ... }
 参数:allow_nil boolean 设为true时跳过nil对象.
   :on :save, :create, or :update
 实例:
 class User < ActiveRecord::Base
  validates_each :name, :email do |model, attr, value|
   if value =~ /groucho|harpo|chico/i
    model.errors.add(attr,"You can't be serious, #{value}")
   end
  end
 end

validates_exclusion_of
 确定被检对象不包括指定数据
 用法:validates_exclusion_of attr..., :in => enum [ options... ]
 #enum指一切可用include?()判断的范围.
 参数:allow_nil 设为true将直接跳过nil对象.
   :in (or :within) enumerable 
   :message text 默认为: “is not included in the list.”
   :on :save, :create, or :update
 实例:
 class User < ActiveRecord::Base
  validates_exclusion_of :genre,
            :in => %w{ polka twostep foxtrot },
            :message =>"no wild music allowed"
  validates_exclusion_of :age,
             :in => 13..19,
             :message =>"cannot be a teenager"
 end

validates_inclusion_of
 确认对象包括在指定范围
 用法:validates_inclusion_of attr..., :in => enum [ options... ]
 参数:allow_nil 设为true直接跳过nil对象
   :in (or :within) enumerable An enumerable object.
   :message text 默认:“is not included in the list.”
   :on :save, :create, or :update
 实例:
 class User < ActiveRecord::Base
  validates_inclusion_of :gender,
            :in => %w{ male female },
            :message =>"should be 'male' or 'female'"
  validates_inclusion_of :age,
            :in => 0..130,
            :message =>"should be between 0 and 130"
 end

validates_format_of
 用正则检验对象
 用法:validates_format_of attr..., :with => regexp [ options... ]
 参数:message text 默认为: “is invalid.”
   :on :save, :create, or :update
   :with 正则表达式
 实例:
 class User < ActiveRecord::Base
  validates_format_of :length, :with => /^\d+(in|cm)/
 end

validates_length_of
 检查对象长度
 用法:validates_length_of attr..., [ options... ]
 参数:in (or :within) range 
   :is integer 
   :minimum integer 
   :maximum integer 
   :message text 默认文字会根据参数变动,可使用%d 取代确定的最大,最小或指定数据.
   :on :save, :create, or :update
   :too_long text 当使用了 :maximum后的 :message 
   :too_short text ( :minimum )
   :wrong_length ( :is)
 实例:
 class User < ActiveRecord::Base
  validates_length_of :name, :maximum => 50
  validates_length_of :password, :in => 6..20
  validates_length_of :address, :minimum => 10,
                :message =>"seems too short"
 end

validates_numericality_of
 检验对象是否为数值
 用法:validates_numericality_of attr... [ options... ]
 参数:message text 默认 “is not a number.”
   :on :save, :create, or :update
   :only_integer 
 实例:
 class User < ActiveRecord::Base
  validates_numericality_of :height_in_meters
  validates_numericality_of :age, :only_integer => true
 end

validates_presence_of
 检验对象是否为空
 用法:validates_presence_of attr... [ options... ]
 参数:message text 默认:“can’t be empty.”
   :on :save, :create, or :update
 实例:
 class User < ActiveRecord::Base
  validates_presence_of :name, :address
 end

validates_uniqueness_of
 检验对象是否不重复
 用法:validates_uniqueness_of attr... [ options... ]
 参数:message text 默认: “has already been taken.”
   :on :save, :create, or :update
   :scope attr 指定范围,用于组合校验
 实例:
 class User < ActiveRecord::Base
  validates_uniqueness_of :name
 end

 class User < ActiveRecord::Base
  validates_uniqueness_of :name, :scope =>"group_id"
 end
 #指定在同一group_id的条件下不重复.

常用正则:

E-Mail地址格式:
validates_format_of     :email,
                        :with       => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                        :message    => 'email must be valid'

网址格式:
validates_uri_existence_of :url, :with =>
        /(^$)|(^(http|https)://[a-z0-9] ([-.]{1}[a-z0-9] )*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix

Validation Helpers

有些确认是平常:这个属性必须不能为空,其它属性必须在1865之间等等。“活动记录”有一套标准的帮助方法来添加这些确认给你的“模型”。每个都是类级别方法,所有名字都以validates_开头。每个方法接受可选的属性名字列表,它是由配置选项的哈希表提供给确认的。

例如,我们可以这样写先前确认

class User < ActiveRecord::Base

validates_format_of :name,

:with => /^w+$/,

:message => "is missing or invalid"

validates_uniqueness_of :name,

:on => :create,

:message => "is already being used"

end

大多数validates_methods接受:on:message选项。:on选项确定何时应用确认并接受:save(缺省的):create,或:update中的一个。:message参数可以用生成错误消息覆写它。

确认失败时,帮助方法添加一个error对象给“活动记录”“模型”对象。这将被关联到被确认的字段。在确认之后,你可以查看“模型”对象的errors属性来访问错误列表。当“活动记录”被用做Rails应用程序一部分时,这个检查通常由两个步骤完成:

1、“控制器”试图保存一个“活动记录”对象,但因为确认的原因保存失败了 (返回false)“控制器”将重新显示包含错误数据的表单。

2、“视图模板”使用error_messages_for()方法来显示“模型”对象的错误列表,并且用户有机会来修正字段。

http://sunac400.blog.163.com/blog/static/22658271200702243452435/



附加一段例子

class Product < ActiveRecord::Base

    validates_presence_of :title,:description ,:image_url

    validates_numericality_of :price

    validates_uniqueness_of :title

    validates_format_of :image_url,:with=>%r{\.(gif|jpg|png)$}i ,:message=>'must be a url for gif,jpg,png image.'

    validates_length_of :title ,:minimum=>4,:maximum=>50,:message=>"title must be in 4~50."

    

    validate:price_must_be_at_least_a_cent

    protected

    def price_must_be_at_least_a_cent

        errors.add(:price,'should be at least 0.01') if price.nil?|| price<0.01

    end

end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值