Ruby on Rails 的模型 validates 验证
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 验证的更多相关文章
- Ruby on Rails 单元测试
Ruby on Rails 单元测试 为什么要写测试文件? 软件开发中,一个重要的环节就是编写测试文件,对代码进行单元测试,确保程序各部分功能执行正确.但是,这一环节很容易被我们轻视,认为进行单元测试 ...
- Ruby on Rails Tutorial读书笔记-1
只是怕忘了命令,全部撸一次,记个大概.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 安装Ruby之前,先要安装RVM: curl -L https://get.rvm.io | bas ...
- Ruby on Rails框架开发学习
学习地址:http://www.ixueyun.com/lessons/detail-lessonId-685.html 一.课程概述 软件开发在经历了面向过程编程的阶段,现在正大行其道的是敏捷开发, ...
- [Ruby on Rails系列]3、初试Rails:使用Rails开发第一个Web程序
本系列前两部分已经介绍了如何配置Ruby on Rails开发环境,现在终于进入正题啦! Part1.开发前的准备 本次的主要任务是开发第一个Rails程序.需要特别指出的是,本次我选用了一个(Paa ...
- Ruby on Rails 开发笔记
安装 Ruby on Rails Install Rails: A step-by-step guide 创建应用 # 创建新的应用程序 $ rails new blog $ cd blog # 启动 ...
- 开发新手最容易犯的50个 Ruby on Rails 错误(1)
[编者按]本文最早发布与 JETRuby 博客,主要介绍了开发新手最容易犯的 Ruby 错误.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 一年前,我们创立了以 "Rubyboo ...
- 《Ruby on Rails教程》学习笔记
本文是我在阅读 Ruby on Rails 教程的简体中文版时所做的摘录,以及学习时寻找的补充知识.补充知识主要来自于 Ruby on Rails 實戰聖經. Asset Pipeline 在最新版 ...
- Windows下: RubyMine + Ruby On Rails + mysql 搭建开发环境
最近在接手一个手机项目.在搭建环境的过程中,遇到了一些问题,在下文中已做记录,并奉上个人的解决方案. 开发环境 win2003 ; JetBrains RubyMine6.3.3 1. 下载最新版 ...
- [ruby on rails] 跟我学之(3)基于rails console的查增删改操作
本章节展开对model的介绍:包括查增删改操作.紧接着上面一节<[ruby on rails] 跟我学之HelloWorld> 创建模型 使用命令创建模型 创建表post,默认自带两栏位 ...
随机推荐
- BootStrap【三、组件】
特有标签属性 role 用于浏览器识别 aria-label 用于浏览器识别 tabIndex 用于浏览器识别 data- 自定义数据属性 图标 直接引用官方图标库中的class 官方图标库 Demo ...
- C# 一个数组集合,任意组合,不遗漏,不重复
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using S ...
- GOLANG的继承语法练习
package main import( "fmt" _"sort" _"math/rand" ) // type WuDangMaster ...
- web开发:清浮动
一.display总结 二.overflow 三.浮动布局 四.清浮动 五.清浮动的方式 一.display总结 <!DOCTYPE html> <html> <head ...
- 12_Redis_服务器命令
一:Redis 服务器:Redis 服务器命令主要是用于管理 redis 服务
- vim编辑命令
vi命令 命令模式: yy:复制 光标所在的这一行 4yy:复制 光标所在行开始向下的4行 p: 粘贴 dd:剪切 光标所在的这一行 2dd:剪切 光标所在行 向下 2行 D:从当前的光标开始剪切,一 ...
- fixed固定元素
1.css <style type="text/css"> .elementFixed{ position: fixed; top:0; } </style> ...
- python之global用法
如果需要在函数内部改变函数外部的变量,就可以通过在函数内部声明变量为global变量.这样当程序运行至global变量便会替换外部的同名变量. 例1: # -*- coding:utf-8 -*- n ...
- mongodb的安装与使用(一)
一.什么是MongoDB ? MongoDB一种由C++语言编写的,是一个基于分布式文件存储的非关系型数据库(NoSql),是一种强大.灵活.可扩展的数据存储方式,因为MongoDB是文档模型,数据结 ...
- vue cli 3.x 配置使用 sourceMap
项目使用vue cli 3.x搭建,没有了配置文件,如何更方便的查找到对应的scss文件,配置项目支持sourceMap方式? 分二步走: 1.项目根目录(不是src目录,不要搞错了)添加vue.co ...