rails表单校验功能讨论

rails针对model提供了完善的校验功能,但有时候,我们的表单并不对应到model,比如login表单,比如search表单,这方面rails并没有给出很好的解决方案(verify太简陋),我是这么实现的(实验阶段):

1、修改ApplicationController
[code]
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
[/code]

2、需要检验的Controller增加检验配置:
[code]
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
[/code]

3、增加表单:
[code]
<%
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%>
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值