Rails提供一系列用于验证用户输入内容的方法(详细的API文档 )
用户输入内容验证的实现逻辑是:
以下是一个简单的示例验证用户发帖时的输入内容。
控制器
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 validation on Rails