Ruby On Rails: Validate atleast one Checkbox is Checked in a Form

Lets say you have a form with the following checkboxes.

<%= f.check_box :checkbox1 %>
<%= f.check_box :checkbox2 %>
<%= f.check_box :checkbox3 %>

Now to make sure atleast one checkbox is checked, add the following code to your model.

  validate :atleast_one_is_checked

  def atleast_one_is_checked
    errors.add(:base, "Select atleast one output format type") unless checkbox1 || checkbox2 || checkbox3
  end

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

1 comment

Leave a Reply