手把手教你学习ROR-5.Validation

Rails应用一般有三层校验

1 在Client端,可以使用JQuery-Validation 框架

2 在Controller端,配置Model时的validate,会在Controller调用save,update之前进行校验

  • create
  • create!
  • save
  • save!
  • update
  • update!

3 Database,在schema中设置

 

A 校验方法

1 校验存在性

validates :email,:password, presence: true

 

2 校验字段长度

validates :nickname, length: { minimum: 2,maximum:20}

 

3 验证唯一性

validates :email, uniqueness: true

 

4 校验格式

validates :email, format: { with:/@/}

 

5 校验是否为数字

validates :user_id, numericality: { only_integer: true }

 

6 验证字段是否不存在,string是否为空或者为“”,可以用present校验这个字段

validates :name, :login, :email, absence: true

 

7 验证某个字段是否在集合内

 validates :size, inclusion: { in: %w(small medium large), message: "%{value} is not a valid size"}

 

8 验证某个字段不在集合内

validates :domain, exclusion: { in: %w(www us ca jp), message: "Subdomain %{value} is reserved."}

 

9 用自己的Valiator类来进行校验

validates_with GoodnessValidator, fields: [:first_name, :last_name]

 

10 需要确认confirmation进行校验

 validates :email, confirmation: true

 

B 其他字段

1allow_nil

validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_nil: true

 

2 allow_blank

validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_blank: true

 

3 message

validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_nil: true

 

4 on

validates :email, uniqueness: true, on: :create

 

5 strict(可以自己定制Exception,当validate不通过时,raise Exception)

validates :token, presence: true, uniqueness: true, strict: TokenGenerationException

 

6 if

validates :surname, presence: true, if: "name.nil?"

 

7 unless

validates :surname, presence: true, unless: "name.nil?"

 

C Validation in the view

<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

  

 

posted on 2013-11-12 17:02  soulspirit  阅读(308)  评论(0)    收藏  举报