Ruby on Rails 中文 Wiki
如何验证用户输入 (changes)

显示修订历史自 #0 至 #1: 添加 | 移除

在Rails中验证用户提交的内容

Rails提供一系列用于验证用户输入内容的方法(详细的API文档

用户输入内容验证的实现逻辑是:

  1. 在数据模型(Model)中使用Rails提供的宏方法,或者您自定的验证方法,在记录创建或更新适合进行验证
  2. 如果验证失败,所产生的错误消息对象会被保存在该数据记录的 errors 属性中。并且对这个数据更新的保存工作将失败。
  3. 在 页面模板 (View) 中可以使用 Rails 提供的帮助方法将错误记录渲染输出。

以下是一个简单的示例验证用户发帖时的输入内容。

控制器

class WeblogController < ActionController::Base
  def show # not used directly, just example
    @post = Post.find(params["id"])
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(params["post"])
    if @post.save
      redirect_to :action => "show", :id => @post.id
    else
      render_action "new" 
    end
  end
end

页面模板

<% unless @post.errors.empty? %>
  The post couldn't be saved due to these errors:
  <ul>
  <% @post.errors.each_full do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
<% end %>

<%= form "post" %>

这个页面模板可以通过使用 Rails 提供的错误渲染的帮助方法而精炼成为:

<%= error_messages_for 'post' %>

数据模型

class Post < ActiveRecord::Base
    # 发帖必须包含 标题和内容  
    validates_presence_of :title, :body, :message => "请填写必填项" 
    # 标题不能超过10个字
    validates_length_of :title, :maximum => 10, :message => "标题太长,最多10个字" 
end

通过 Ajax 进行输入验证

如果你需要通过Ajax在页面中实现用户输入验证(比如在注册页面中判断访客填写的用户名是否已经被注册)

请参见具体实现方法 AJAX validation on Rails

本条目被以下条目链接: