转自:http://www.cslog.cn/Content/ruby_on_rails_validation_helpers

可以自定义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

转载于:https://www.cnblogs.com/odbc/archive/2009/05/14/RubyonRailsValidationHelpers.html

Ruby on Rails 的检验方法(Validation Helpers)大全相关推荐

  1. How to Generate PDF in Ruby on Rails(HowtoGeneratePDFs) ZT

    本文转载自: https://www.cnblogs.com/hardrock/archive/2006/07/24/458184.html 作者:hardrock 转载请注明该声明. This ho ...

  2. ruby on rails_最终的中级Ruby on Rails教程:让我们创建一个完整的应用程序!

    ruby on rails 由Domantas G (By Domantas G) There are plenty tutorials online which show how to create ...

  3. [rails] 我的订餐系统 -- 小试ruby on rails(转)

    前言         近期在java社区中一种新的脚本语言ruby,及用ruby开发的一个wab框架 rails也热闹了起来.引起了不少的java开发人员的关注. 本人平时还是很少接触脚本语言方面东东 ...

  4. Ruby on rails

    转自https://www.cnblogs.com/fantiantian/p/3401913.html Ruby on rails初体验(一) 接触ruby on rails 已经有一段时间了,想记 ...

  5. netbeans下开发rails快捷键 及 Ruby On Rails开发技巧总结

    在controller和view直接跳转 - Ctrl + Shift + A 在controller/model和test/spec之间跳转 - Ctrl + Shift + T 直接跳转到类和方法 ...

  6. react前端项目_如何使用React前端设置Ruby on Rails项目

    react前端项目 The author selected the Electronic Frontier Foundation to receive a donation as part of th ...

  7. Ruby On Rails 4 hello world,Ruby On Rails上手

    有机会再试一试Rails了,只是原来接触的是2,现在已然变成了4,似乎现在的安装比原来会快些.. Rails 4 安装 针对于安装了RVM gem install rails 没有的话应该主 sudo ...

  8. ruby on rails win下安装

    ruby on rails win下安装 发现新的技术ruby on rails,关于他一些介绍就不说了,我说下今天的我的安装过程! 首先是下载 http://rubyforge.org/projec ...

  9. windows下安装ruby on rails

    1.首先去 http://rubyforge.org/frs/?group_id=167 找一个One-Click Ruby Installer下载下来 2.安装One-Click Ruby Inst ...

最新文章

  1. 【基本操作】主席数统计区间不同颜色个数
  2. 2019微生物组—宏基因组分析专题培训开课啦!
  3. eclipse安装SVN插件的两种方法
  4. RuntimeError Assertion cur_target = 0 cur_target n_classes failed
  5. 开发日记-20190822 关键词 读书笔记《Unix环境高级编程(第二版)》《掌控习惯》DAY 2
  6. Fragment之间的通信
  7. php png 透明缩略图,php生成图片缩略图,支持png透明
  8. 15张图带你彻底明白spring循环依赖,再也不用怕了
  9. ESP8266多功能点阵时钟 - PCB制作分享
  10. 银河麒麟服务器无raid驱动安装处理
  11. Excel函数-数据库函数大全(Excel Database Functions)
  12. 基于51单片机的避障小车
  13. 三凌PLC源码,STM32F205VCT6主控PLC控制器板,已批量生产
  14. 微信聊天内容制作生成器微信小程序源码/支持多种制作生成
  15. Unity Input键盘输入无反应
  16. 计算机怎么打字快,电脑新手如何快速打字?
  17. iOS完全免费的4个APP,良心安利!谁说便宜没好货
  18. 操作系统对计算机组件的抽象概念表示
  19. 云端守望者(下):十八般武艺
  20. 微信支付宝个人收款解决方案之免签约支付解决方案之APP监控通知方案

热门文章

  1. courses to choose
  2. Agile Development
  3. 算法笔记 1 31 chapter4
  4. Linux 上扩展swap分区
  5. Quick BI助力云上大数据分析---深圳云栖大会
  6. [raspberry pi3] 串口线使用
  7. 基本数据结构之BinarySearchTree
  8. java设计模式_工厂方法
  9. Kickstart 多系统安装配置
  10. 基于.Net Remoting的项目总结报告