【问题标题】:How to validate Rails form_for is completely filled out on the client side?如何验证 Rails form_for 是否在客户端完全填写?
【发布时间】:2014-09-06 02:18:26
【问题描述】:

在允许将表单提交到后端之前,我很难验证 Rails form_for 中的所有表单字段是否都已完成。在背面,模型检查所有属性是否存在,但在前面,如果用户没有填写字段,我需要提醒他们。表格如下:

<h1>List an item for sale</h1>
<%= form_for Product.new, :options => {:id => "new_listing"}, :url => {:action => "create"}, :html => {:multipart => true} do |f| %>
  <div><%= f.label :name %><br />
    <%= f.text_field :name, :id => "name_input", :autofocus => true, :placeholder => "Name yourself" %>
  </div>
  <div><%= f.label :price %><br />
    <%= f.number_field :decimal_price, :step => 'any', :placeholder => "Name your price" %>
  </div><br />
  <div><%= f.label :description %><br />
    <%= f.text_area :description, :cols => "50", :rows => "10", :placeholder => "Write a few sentences about the item you're listing. Is it in good condition? Are there any accessories included?" %>
  </div>
  <div>
    <%= f.label "Add a photo (increases your likelihood of selling)" %><br />
    <%= f.file_field :photo %>
  </div>
  <br />
  <div>
    <%= f.label "Category" %><br />
    <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => 'Choose a category' %>
  </div><br />
  <%= f.submit "List!" %>
<% end %> 

我遇到的问题是弄清楚如何将错误的布尔值发送到表单,以便阻止发送表单。每次我尝试使用 onSubmit 或 onclick 操作时,它都会提交并忽略错误的布尔值。有人可以告诉我如何检查 name_input、price 和 description 的表单字段以确保它们已完成,如果未完成则抛出错误?

【问题讨论】:

标签: javascript jquery ruby-on-rails forms


【解决方案1】:

如果我理解正确...你应该尝试在你的 jQuery 提交处理函数中使用“event.preventDefault()”:

 $( "#your-product-form-id" ).submit(function( event ) {
      if( your_validation_function() )
        return;
      else event.preventDefault();
    });

但对于简单的存在检查,我会在输入字段中添加 html 'required',如下所示:

<%= f.text_field :name, :id => "name_input", :required => true %>

【讨论】:

    【解决方案2】:

    :required =&gt; true怎么样

    &lt;%= f.text_field :name, :id =&gt; "name_input", :autofocus =&gt; true, :placeholder =&gt; "Name yourself", required =&gt; true %&gt;

    【讨论】:

    • 更新 Boomerange 的评论(当时是正确的):在 Safari 10.1(2017 年 3 月 26 日发布)中终于添加了对 HTML5 表单验证的支持。
    【解决方案3】:

    您可以使用 jQuery 将焦点或键绑定到每个字段。从那里,您可以向 Rails 控制器发出 AJAX 请求,以提取您希望验证的值。

    例子:

    $("#name-input").focusout(function(){
      $.ajax({
       type: "GET",
       dataType "JSON",
       url: "insert_path_here"
       success: function(data){
         **INSERT VALIDATION CODE HERE***
       }
    
     }
    });
    

    【讨论】:

      【解决方案4】:

      在输入所有必需信息之前禁用 JavaScript 中的提交按钮将起作用。只是以某种方式向用户表明缺少信息,一旦输入了某些内容,就可以启用按钮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-25
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-09
        相关资源
        最近更新 更多