Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simply validate a checkbox in rails

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.

like image 903
geirmash Avatar asked Apr 26 '13 13:04

geirmash


2 Answers

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.

like image 185
kostja Avatar answered Sep 19 '22 17:09

kostja


I was able to skip the jQuery portion and get it validation to work with this questions help. My method is below, I'm on Rails 5.1.2 & Ruby 2.4.2.

Put this code in your slim, erb or haml; note syntax may differ slightly in each. The line below was specifically for slim.

f.check_box :terms_of_service, required: true 

I used a portion of kostja's code suggestion in the model.

validates :terms_of_service, :acceptance => true
like image 23
jasmineq Avatar answered Sep 19 '22 17:09

jasmineq