简体   繁体   中英

simple_form validations with Bootstrap in Rails

I have the following simple_form in my rails app:

<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. I have tried adding f.error fields for each input but that does not seem to do anything.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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