Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Form Select Required

I am trying to have a <select> be required in my Rails form.

This is my code (elipsis is to make line shorter):

<div class="field">
  <p><%= f.label :category, "Category:" %></p>
  <%= f.select :category, ['Analytics','Commerce',..., 'Web'], :prompt => '-- Select One --', :required => true %>
</div>

Which outputs

<div class="field">
  <p><label for="startup_category">Category:</label></p>
  <select id="startup_category" name="startup[category]">
    <option value="">-- Select One --</option>
    <option value="Analytics">Analytics</option>
    <option value="Commerce">Commerce</option>
    <option value="Content Management">Content Management</option>
    <option value="Gaming">Gaming</option>
    <option value="Green">Green</option>
    <option value="Media">Media</option>
    <option value="Social Media">Social Media</option>
    <option value="Technology - Software">Technology - Software</option>
    <option value="Technology - Hardware">Technology - Hardware</option>
    <option value="Web">Web</option></select>
</div>

Putting {:required => true} instead of :required => true gives a syntax error and {:prompt => '-- Select One --', :required => true} renders the page, but without the required="true" in my select tag.

How can I get required="true" in my tag?

like image 868
Michael Johnston Avatar asked Apr 21 '13 20:04

Michael Johnston


3 Answers

try this one....

f.select :category, ['Analytics','Commerce',..., 'Web'], { :include_blank => '-- Select One --' }, :required => true
like image 180
Aditya Kapoor Avatar answered Oct 31 '22 22:10

Aditya Kapoor


For Rails 4

    f.select :category,
      ['Analytics','Commerce',..., 'Web'],
      {
        include_blank: '-- Select One --' ,
        required: true
      }
like image 21
Mugur 'Bud' Chirica Avatar answered Oct 31 '22 21:10

Mugur 'Bud' Chirica


I am not sure if it accomplish what you want, but I have two solutions for you. You can use simpleform gem.

OR

Style it:

<label class="required">Category</label>

The in css:

label.required:after{content:"*"}
like image 42
Przemek Mroczek Avatar answered Oct 31 '22 20:10

Przemek Mroczek