浏览 2722 次
锁定老帖子 主题:rails表单校验功能讨论
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2007-12-25
1、修改ApplicationController class << self def validate_action(action_name,options={}) config = {} yield config if block_given? return false if config.empty? filter_opts={:only => action_name.to_sym} options={:render=>{:action=>action_name.to_s}} if options[:render].nil? || options[:redirect_to].nil? before_filter(filter_opts) do |c| c.send :validates,config,options end end end private def validates(validate_options={},options={}) @errors = {} has_error=false validate_options.each do |key,config| field = key.to_sym if params[field].nil? or params[field].empty? @errors[field] = config[:message] || "" has_error = true end end if has_error unless performed? render(options[:render]) if options[:render] redirect_to(options[:redirect_to]) if options[:redirect_to] end return false else return true end end 2、需要检验的Controller增加检验配置: class TestController < ApplicationController validate_action :test do |config| config[:loginame] = {:message=>"登陆名不能为空"} config[:password] = {:message=>"密码不能为空"} end def index render :action=>"test" end def test redirect_to :controller=>"/" end end 3、增加表单: <% full_messages = [] @errors.each() do|attr,msg| full_messages << msg end unless @errors.nil? %> <%if !full_messages.empty?%> <ol> <%full_messages.each do |msg|-%> <li><%=msg%></li> <%end-%> </ol> <%end%> <%form_tag :action=>"test" do%> <%= text_field_tag "loginame",params[:loginame]%> <%= password_field_tag "password",params[:password]%> <input type="submit"> <%end%> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-12-25
没人讨论自己来
修改了以下,做成插件(无需修改ApplicationControll),可以这样使用: class TestController < ApplicationController validate_action :test do |v| v.required :field=>"loginame",:message=>"登陆名不能为空" v.required :field=>"password",:message=>"密码不能为空" v.string_len :field=>"loginame",:max=>5 end def index render :action=>"test" end def test redirect_to :controller=>"/" end end 刚刚做了两个测试用的校验器required和string_len,很容易就可以增加date、expression、regex校验 |
|
返回顶楼 | |