How to simply validate a checkbox in rails

此生再无相见时 提交于 2019-12-31 22:39:42

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/16237734/how-to-simply-validate-a-checkbox-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!