---
title: "rails 3 新的 验证写法"
author: "fei1985"
date: "2010-04-10T23:25:28Z"
tags: []
categories: ["编程语言"]
slug: "rails-3"
draft: false
lastmod: "2010-04-10T23:28:10Z"
id: 640984
url: "https://1985.iteye.com/blog/640984"
---

在源文件中看到新的写法 和前面相差很多, 不过老方案在rails3也不会出错

 

Examples of using the default rails validators:

  validates :terms, :acceptance =&gt; true  
  validates :password, :confirmation =&gt; true  
  validates :username, :exclusion =&gt; { :in =&gt; %w(admin superuser) }  
  validates :email, :format =&gt; { :with =&gt; /\\A(\[^@\\s]+)@((?:\[-a-z0-9]+\\.)+\[a-z]{2,})\\Z/i, :on =&gt; :create }  
  validates :age, :inclusion =&gt; { :in =&gt; 0..9 }  
  validates :first\_name, :length =&gt; { :maximum =&gt; 30 }  
  validates :age, :numericality =&gt; true  
  validates :username, :presence =&gt; true  
  validates :username, :uniqueness =&gt; true

 

  validates :title, :presence =&gt; true, :uniqueness =&gt; true, :length =&gt; { :maximum =&gt; 100 }  
  validates :budget, :presence =&gt; true, :length =&gt; { :within =&gt; 1..10000000 }

\# Finally, the options :if, :unless, :on, :allow\_blank and :allow\_nil can be given  
      # to one specific validator:  
      #

validates :password, :presence =&gt; true, :confirmation =&gt; true, :if =&gt; :password\_required?

 

感觉比原来的写起来越简单 一个属性的验证方案定义在一起