简体   繁体   English

在Rails中使用Bootstrap进行simple_form验证

[英]simple_form validations with Bootstrap in Rails

I have the following simple_form in my rails app: 我的rails应用程序中具有以下simple_form:

<div class="panel panel-default">
 <div class="panel-heading">
  <h3 class="panel-title center">Add New Customer</h3>
 </div>
  <div class="panel-body">
   <%= simple_form_for(@customer, html: {class:'form-horizontal'}, wrapper: :horizontal_form) do |f| %>
    <%= f.input :first_name, input_html: {class:'form-control'} %>
    <%= f.input :last_name, input_html: {class:'form-control'} %>
    <%= f.input :phone_number, as: :tel, input_html: {class:'form-control'} %>
    <%= f.input :email_address, as: :email, input_html: {class:'form-control'} %>
    <%= f.input :address, input_html: {class:'form-control'} %>
    <%= f.input :city, input_html: {class:'form-control'} %>
    <%= f.input :postal_code, input_html: {class:'form-control'} %>
    <%= f.input :customer_type, collection: ["Retail", "Contractor", "Dealer"], input_html: {class:'form-control'}, prompt: "Select Customer Type" %>
    <br />
    <%= f.button :submit, "Create Customer", class: "col-md-3 bump-right" %>
   <% end %>
  </div>
</div>

As you can see, I'm using bootstrap styling on the form elements. 如您所见,我在表单元素上使用了引导样式。 When I submit the form, I want the following to happen: 提交表单时,我希望发生以下情况:

  1. Validate email 验证电子邮件
  2. Validate phone number 验证电话号码
  3. Require all fields 需要所有字段

As it stands now, when I submit the form, none of the above three happen. 就目前而言,当我提交表格时,以上三个都没有发生。 Looking through the docs for simple_form ( https://github.com/plataformatec/simple_form ) I can't discern what I need to do to achieve my end result. 在文档中寻找simple_form( https://github.com/plataformatec/simple_form ),我无法辨别为达到最终结果而需要做什么。 I have tried adding f.error fields for each input but that does not seem to do anything. 我尝试为每个输入添加f.error字段,但这似乎无济于事。

There is this 2 year old question: simple_form & bootstrap validations not working - but this is foreign to me and given the 2.5 year old versions I'm sure something has changed. 有一个2年的历史问题: simple_form和bootstrap验证不起作用 -但这对我来说是陌生的,考虑到2.5年的版本,我确定已经有所改变。

If anyone has any ideas, or can help me demystify the docs I would be grateful. 如果有人有任何想法,或者可以帮助我揭开文档的神秘面纱,我将不胜感激。

Use validations in the models (specifically the customer model) which would happen before the data is saved to the database. 在模型(特别是客户模型)中使用验证,该验证将在数据保存到数据库之前进行。 See the docs here . 此处查看文档。

Example: 例:

class Person < ActiveRecord::Base
  validates :name, presence: true
end

Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM