【问题标题】:Rails : Check if field is blank on submitRails:检查提交时字段是否为空白
【发布时间】:2015-05-26 13:41:47
【问题描述】:

在 Rails 应用程序中,我有一个搜索字段,如果它是空白的,我必须控制(在提交操作上)。 这个没有连接到用于注册一些数据的表:

 <%= form_tag products_path, :method => 'get' do %>
  <%= text_field_tag :search, params[:search]%>
  <%= submit_tag "Ricerca" %>   
 <% end %>

我已经尝试在我的控制器中定义一个动作来检查我传递的参数的值:

if !(params[:search].present?)
  redirect_to root_path, error: 'Insert a research key'
else
  @count = Product.search(params[:search]).count

  if @count == 0
    redirect_to root_path, error: 'No data found for your search'
  else
    @products = Product.search(params[:search])
  end
end

对通过 Rails 验证我的字段有什么想法吗?

【问题讨论】:

  • 您的代码似乎没问题!。有什么问题

标签: ruby-on-rails validation


【解决方案1】:

您可以同时验证服务器端和客户端。您将始终需要服务器端,因为可以在不使用表单的情况下访问 url,并且您需要一种方法来处理它。客户端将使用户体验更好,因为他们不需要重新加载页面来获得反馈。

对于服务器端,就像if params[:search].blank? 一样简单,这将检查= nil= ""

对于客户端,有两种主要方式。 Javascript 和 HTML 5。使用 HTML 5,您可以将 :required =&gt; true 添加到表单元素中,这就是您所需要的。 使用 javascript,或者在这种情况下使用 JQuery,它可以像这样工作

$('form').submit(function() {  //When a form is submitted...
  $('input').each(function() { //Check each input...
    if ($(this).val() == "") { //To see if it is empty...
      alert("Missing field");//Say that it is
      return false;            //Don't submit the form
    }
  });
  return;                      //If we made it this far, all is well, submit the form
});

【讨论】:

  • 我在 Firefox 上使用了 :required=>true,效果很好,但在 google chrome 上却不行。
【解决方案2】:

您可以在客户端使用 HTML5 验证(您仍然应该进行服务器端检查):

<%= form_tag products_path, :method => 'get' do %>
  <%= text_field_tag :search, params[:search], required: true %>
  <%= submit_tag "Ricerca" %>   
<% end %>

:required =&gt; true 将要求搜索字段中有内容。

【讨论】:

    【解决方案3】:

    将 ActiveModel 用于具有验证的无表模型。

    型号:

    class ExampleSearch
      include ActiveModel::Validations
      include ActiveModel::Conversion
      extend ActiveModel::Naming
    
      attr_accessor :input
    
      validates_presence_of :input
      validates_length_of :input, :maximum => 500
    
    end
    

    和你的表格:

    <%= form_for ExampleSearch.new(), :url=>posts_path, :method=>:get, :validate=>true do |f| %>
      <p>
        <%= f.label :input %><br />
        <%= f.text_field :input, required: true %>
      </p>
      <p><%= f.submit "Search" %></p>
    <% end %>
    

    为了获得良好的用户体验,请使用gem 'client_side_validations'

    关于 ActiveModel 的信息:

    http://railscasts.com/episodes/219-active-model

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2011-08-18
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多