How to simply validate a checkbox in rails
checkbox, ruby-on-rails, validation
Solution
Adding
validates :terms_of_service, :acceptance => true
to your model should do it. Look here for more details and options.
However, if accepting the terms is not part of a form for your model, you should use client-side validations, i.e. JavaScript, like this (in jQuery):
function validateCheckbox()
{
if( $('#checkbox').attr('checked')){
alert("you have to accept the terms first");
}
}
You can add a script file to your view like this:
`<%= javascript_include_tag "my_javascipt_file" %>`
and trigger the function on click:
`<%= submit_tag "Submit", :onclick: "validateCheckbox();" %>`
EDIT: you can assign an id to your checkbox like this: `check_box_tag :checkbox`. The HTML will look like this: `<input id="checkbox"` See these examples for more options.
Problem
How do you simply validate that a checkbox is checked in rails? The checkbox is for a end user agreement. And it is located in a modal window. Lets say i have the checkbox: ``` <%= check_box_tag '' %> ``` Where and how should i validate this? I have seen most posts about checkbox validation in rails here, but none of them suit my needs.