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,默认自带两栏位 ...
随机推荐
- RabbitMQ消息分发轮询
一,前言 如果我们一个生产者,对应多个消费者,rabbitmq 会发生什么呢 二,消息分发轮询 前提条件:1个生产者 ----> 多个消费者,且no_ack=True (启动三次生产者) ① ...
- 基础网络之EfficientNet
摘要: 一般情况下,我们都会根据当前的硬件资源来设计相应的卷积神经网络,如果资源升级,可以将模型结构放大以获取更好精度.我们系统地研究模型缩放并验证网络深度,宽度和分辨率之间的平衡以得到更好的性能表现 ...
- windows10 L2tP nat 下无法连接的处理
事件查看器中没有错误代码显示. Windows 10 L2TP/IPsec Manual Setup Instructions Bold items are things you will click ...
- org.apache.tomcat.util.descriptor.web.WebXml.setVersion Unknown version string [4.0]
错误: 在 IDEA 创建WEB项目之后,打印出的日志中总是出现一行警告信息: 12-May-2018 15:52:30.692 警告 [RMI TCP Connection(3)-127.0.0.1 ...
- PHPStorm 3.3 破解方法 以及汉化
第一步修改host文件(host文件地址为): C:\Windows\System32\drivers\etc 将以下内容添加到host文件里面 0.0.0.0 account.jetbrai ...
- hexo不蒜子网站访问量统计失效
问题 hexo博客的不蒜子网站访问量统计最近失效了. 解决 原因 不蒜子域名更改了,所以需要修改博客的配置文件. 方法 进入博客目录下\themes\next\layout\_third-party\ ...
- go语言日期时间格式化
原文: http://www.golangprograms.com/get-current-date-and-time-in-various-format-in-golang.html package ...
- P5650 基础字符串练习题
设定'0'权值为1,设定'1'权值为-1 然后就是最大子段和 #include <cstdio> #include <algorithm> #include <cstri ...
- C# 设置程序开机自启动
设置启动 //设置开机自启动 string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; Reg ...
- BZOJ 2013 : [Ceoi2010]A huge tower / Luogu SP6950 CTOI10D3 - A HUGE TOWER
传送门 菜鸡.jpg CODE #include <bits/stdc++.h> using namespace std; const int MAXN = 620005; int n, ...