geirmash
geirmash

Reputation: 136

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.

Upvotes: 7

Views: 17819

Answers (3)

liamthorne4
liamthorne4

Reputation: 365

Adding on to what has been said already, if you want to add a custom error message, you can add the following to your form:

f.input :terms_of_service, as: :boolean

and then add the following to your model:

validates :terms_of_service, acceptance: { message: "must be accepted"}

Error messages will start with the field name by default followed by your custom message (e.g. Terms of service [CUSTOM MESSAGE]). Something I also found useful was to include a link to the terms of service in the label so users can easily access it to see what they are agreeing to:

f.input :terms_of_service, as: :boolean, label: "I agree to the #{link_to "terms of service", [TERMS AND CONDITIONS PATH]}".html_safe

Upvotes: 0

jasmineq
jasmineq

Reputation: 521

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

Upvotes: 3

kostja
kostja

Reputation: 61538

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.

Upvotes: 20

Related Questions