【发布时间】: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验证库吗?我对这个很幸运(只要验证不是非常复杂):jqueryvalidation.org
标签: javascript jquery ruby-on-rails forms