Reputation: 2224
<%= form_for @organization do |f| %>
<%= render partial: 'shared/error_messages', locals: { object: f.object } %>
<label id="icon" for="country"></label>
<%= f.select :country, [['Afghanistan', 'AF'],
['Albania', 'AL'],
# etc.,
['Zimbabwe', 'ZW']
], {:prompt => 'Please select location', required: true} %>
<label id="icon" for="id_number"></label>
<%= f.text_field :id_number, placeholder: 'e.g.: 123abc' %>
<%= f.check_box(:no_id) + "  <i>No ID</i>".html_safe %>
<% end %>
In a signup form I have the above code. How can I achieve the following for this form?
1) How to make country
required? It currently does accept it when no country is selected despite required: true
. Perhaps it also sees the "Please select location" as a value?
2) How to make it required to either enter an id_number
or to check the box for no_id
, and it's not possible to have both. I would like this requirement for the form as well as at a model level.
Update: I added the model validation below for the 2nd requirement, which seems to work:
validate :id_or_no_id
def id_or_no_id
if (self.id_number.nil? || self.id_number.empty?) && self.no_id != true
errors.add(:id_number, "Need id or need to select checkbox")
elsif (self.id_number && !self.id_number.empty?) && (self.no_id && self.no_id == true)
errors.add(:id_number, "Can't have both id and checked checkbox")
end
end
How can I get the form validation for country
to work? If I change the last line for f.select
to ], {}, {:required => true, :placeholder => 'Select your location...'} %>
an empty line is at the top of the drop-down box (so the placeholder isn't working) and if not selecting a country, then the form validation works in that it asks to select a country. But now the placeholder isn't working...
Upvotes: 0
Views: 71
Reputation: 2280
make sure your model is having validations
class Model
validates :country, presence: true
validates :id_or_no_id
private
def id_or_no_id
if #custom logic here#
errors.add :some_field, "you must have a valid id or no id"
end
end
end
based on your edit, your function should look like this, for better coding (which is also ugly code)
validate :id_or_no_id
def id_or_no_id
if (id_number.nil? || id_number.empty?) && !no_id
errors.add(:id_number, "Need id or need to select checkbox")
elsif (id_number && id_number.present?) && no_id
errors.add(:id_number, "Can't have both id and checked checkbox")
end
end
maybe this is also working
validate :use_one_id
def use_one_id
if !id_number && !no_id
errors.add :id_number, "you must select one...."
end
if id_number && no_id
errors.add :id_number, "can't select both"
end
end
Upvotes: 1