论坛首页 编程语言技术论坛

rails表单校验功能讨论

浏览 2722 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-12-25  
rails针对model提供了完善的校验功能,但有时候,我们的表单并不对应到model,比如login表单,比如search表单,这方面rails并没有给出很好的解决方案(verify太简陋),我是这么实现的(实验阶段):

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%>
   发表时间: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校验
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics