本文介绍了如何简单地验证rails中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何简单地验证在rails中选中了复选框?
该复选框用于最终用户协议。



假设我有复选框:

 

code><%= check_box_tag''%>



我在哪里以及如何验证?

$

解决方案

我已经在rails看过大多数关于checkbox验证的帖子,但没有一个符合我的需要。 div>

添加

 验证:terms_of_service,:acceptance => true 

有关详情和选项,请。



但是,如果接受条款不是模型的表单的一部分,您应该使用客户端验证,即JavaScript,像这样(在jQuery中):

  function validateCheckbox()
{
if($('#checkbox')。attr('checked')){
alert (你必须先接受条款);
}
}

您可以像这样将脚本文件添加到视图:



<%= javascript_include_tagmy_javascipt_file%>



并触发该函数:



<%= submit_tagSubmit,:onclick:validateCheckbox 。 %>



编辑:您可以为此复选框分配一个ID,例如: check_box_tag:checkbox 。 HTML将如下所示:< input id =checkbox请参阅了解更多选项。


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.

解决方案

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.

这篇关于如何简单地验证rails中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:20