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" %>

<%= password_field "user", "password_confirmation" %>

#第二表名为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

Ruby on Rails 的模型 validates 验证的更多相关文章

  1. Ruby on Rails 单元测试

    Ruby on Rails 单元测试 为什么要写测试文件? 软件开发中,一个重要的环节就是编写测试文件,对代码进行单元测试,确保程序各部分功能执行正确.但是,这一环节很容易被我们轻视,认为进行单元测试 ...

  2. Ruby on Rails Tutorial读书笔记-1

    只是怕忘了命令,全部撸一次,记个大概.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 安装Ruby之前,先要安装RVM: curl -L https://get.rvm.io | bas ...

  3. Ruby on Rails框架开发学习

    学习地址:http://www.ixueyun.com/lessons/detail-lessonId-685.html 一.课程概述 软件开发在经历了面向过程编程的阶段,现在正大行其道的是敏捷开发, ...

  4. [Ruby on Rails系列]3、初试Rails:使用Rails开发第一个Web程序

    本系列前两部分已经介绍了如何配置Ruby on Rails开发环境,现在终于进入正题啦! Part1.开发前的准备 本次的主要任务是开发第一个Rails程序.需要特别指出的是,本次我选用了一个(Paa ...

  5. Ruby on Rails 开发笔记

    安装 Ruby on Rails Install Rails: A step-by-step guide 创建应用 # 创建新的应用程序 $ rails new blog $ cd blog # 启动 ...

  6. 开发新手最容易犯的50个 Ruby on Rails 错误(1)

    [编者按]本文最早发布与 JETRuby 博客,主要介绍了开发新手最容易犯的 Ruby 错误.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 一年前,我们创立了以 "Rubyboo ...

  7. 《Ruby on Rails教程》学习笔记

    本文是我在阅读 Ruby on Rails 教程的简体中文版时所做的摘录,以及学习时寻找的补充知识.补充知识主要来自于 Ruby on Rails 實戰聖經. Asset Pipeline 在最新版 ...

  8. Windows下: RubyMine + Ruby On Rails + mysql 搭建开发环境

    最近在接手一个手机项目.在搭建环境的过程中,遇到了一些问题,在下文中已做记录,并奉上个人的解决方案. 开发环境 win2003 ;  JetBrains RubyMine6.3.3 1.  下载最新版 ...

  9. [ruby on rails] 跟我学之(3)基于rails console的查增删改操作

    本章节展开对model的介绍:包括查增删改操作.紧接着上面一节<[ruby on rails] 跟我学之HelloWorld> 创建模型 使用命令创建模型 创建表post,默认自带两栏位 ...

随机推荐

  1. 桌面Ubuntu卡死解决方案

    通常情况下,我们用桌面Ubuntu会遇到卡住的的情况,我们一般会进行强制关机处理,但其实还有另一种操作,不用强制关机. 切换到tty模式,执行命令pkill X;start X;就能重新进入桌面,不用 ...

  2. 【linux】ubuntu修改系统时间

    ubuntu修改时间步骤 ① 先把系统校验时间的程序停止掉 /lib/systemd/systemd-timesyncd systemd 开始,包括了一个名为systemd-timesyncd 的守护 ...

  3. selenium八种定位元素方法

    1.driver.find_element_by_id('su') 定位到元素的id一般id是唯一的,可以精确定位到元素 2.driver.find_element_by_name() 通过元素的na ...

  4. ServiceLoader在SPI中的重要作用分析

    对于线程上下文类加载器在之前已经对它进行了详细的理论化的学习,其中对于这个类加载器应用最多的也就是在SPI场合下用来打破双亲委托机制,如之前所描述的: 这次举一个具体的例子来进一步的加深对线程上下文类 ...

  5. 常量和iota

    定义常量时如果不是必须指定特定类型,可以省略类型,使用默认类型.且数值类型常量(不定义类型)可以直接进行运算 常量的值可以是表达式,但是不允许出现变量 func main() { const a st ...

  6. jquery.table2excel,将HTML的table标签数据导出成excel

    <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content=&quo ...

  7. shell字符串处理

    一.字符串切片: ${#var}:返回字符串变量var的长度${var:offset}:返回字符串变量var中从第offset个字符后(不包括第offset个字符)的字符开始,到最后的部分,offse ...

  8. CSS权重;慎用!important

    初初接触样式的前端开发者在碰到样式覆盖时,最先选择的往往是!important. 但是这种做法不好,应该优先考虑从样式的级联属性或者位置来解决问题. 切记以下情况永远不要使用!important: 1 ...

  9. 有关 C# WebAPI知识

    1.[懒得安分博客总结的很全面] 2.关于基础类型作入参数的问题      参照此博客[ASP.NET WebAPI String 传值问题] 3.代码说明     using System; usi ...

  10. BZOJ 1922: [Sdoi2010]大陆争霸 Dijkstra

    Code: #include <queue> #include <vector> #include <cstdio> #include <cstring> ...