0

I have the following simple_form_for that sends an email using MailForm (does not store anything on a database)

  <div class="small-10 small-offset-1 medium-6 medium-offset-3 large-6 large-offset-3 columns">
    <%= simple_form_for @contact, :html => {:class => 'form-horizontal'} do |f| %>
        <%= f.label :Nombre %>
        <%= f.text_field :name, :required => true, :value => 'Administrador', :readonly => true %>
        <%= f.label :Correo_electrónico %>
        <%= f.email_field :email, :required => true, :value => @pass_email, :readonly => true %>
        <%= f.label :Mensaje %>
        <%= f.text_area :message, :as => :text, :required => true, cols: 20, rows: 10 %>
        <div class="hidden">
          <%= f.input :nickname, :hint => 'Leave this field blank!' %>
        </div>

        </br>
        <%= f.button :submit, 'Enviar', :class => "button [radius round]" %>
    <% end %>
    <%= button_to 'Volver', manager_admin_menu_path, :method => :get, :class => 'button success [radius round]' %>
  </div>

As you can see the text_area has a required => true but when I test the form it allows to submit empty text in the text_area

How can I validate with rails/ruby that any text was typed in the text_area (basically make the text_area it a required field, I know I can probably do this with javascript but want to learn the correct Ruby/Rails way)

UPDATE

My model inherits from MailForm and is defined like this

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha  => true

end

I also want to understand why the required option is not behaving as expected

The texarea is being rendered like this

<textarea cols="20" id="contact_message" name="contact[message]" required="required" rows="10">
</textarea>

Apparently no white spaces but a linebreak is present, does this affect ?

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99

1 Answers1

3

That's the concept of validations in Rails. Validations mean that you make sure a field meets some requirements before saving it to the database, you can validate presence which will only submit the form if the the field is not empty, you can validate uniqueness which will only submit the form if the field is unique ( does not exist already in the database ), and so on.

So for your concern, you have a Contact model, in your contact.rb file you should add :

class Contact <  ActiveRecord::Base 
  validates :message, presence: true // add this line
end

Now when you submit the form with empty message field, it will complain and give you an error.

Read here for more into http://guides.rubyonrails.org/active_record_validations.html

Ahmad Al-kheat
  • 1,805
  • 2
  • 16
  • 25