保存Rails之前的验证

时间:2013-01-27 18:19:34

标签: javascript ruby-on-rails ruby-on-rails-3 forms validation

我想在保存之前执行验证,方法是在提交表单之前确定用户是否填写了特定字段,下面的付款金额字段和选择状态=“已关闭”。如果他没有另一个,那么表格不应该保存

修改页面

<%= simple_form_for @invoice, :html => { :class => 'form-horizontal' } do |f| %>
<%= render "shared/error_messages", :target => @invoice %>

<%= f.association :customer, disabled: @invoice.persisted? %>
<%= f.input :due_date, as: :string, input_html: { class: "datepicker" }, disabled:  @invoice.persisted? %>
<%= f.input :invoice_date, as: :string, input_html: { class: "datepicker" }, disabled: @invoice.persisted? %>
<%= f.input :payment_method, as: :select, :collection => [['Cash','Cash'],['Cheque','Cheque'],['In-House transfer','In-House transfer'],['Account Ledger','Account ledger']], :selected => ['Cash','Cash'] %>
<%= f.input :reference_no, :label => 'Payment Reference No', as: :string %>
<%= f.input :amount, as: :string %>
<%= f.input :payment_date, as: :string, input_html: {class: "datepicker"} %>
<%= f.input :status, as: :select, collection: Invoice::VALID_STATUS %>
Invoice.rb中的

VALID_STATUS = ['草稿','打开','关闭','无效']

我希望如果用户将状态更改为已关闭,则他应该在表单中输入金额。用户不应在未输入金额的情况下将状态更改为已关闭

3 个答案:

答案 0 :(得分:2)

在模型中(app/models/invoice_model.rb)put

validate :close_must_have_amount

然后定义它(相同的文件)

def close_must_have_amount
  :status == 'closed' && :amount # May need to tweak this
end

要在客户端应用模型级验证,您可以使用
https://github.com/bcardarella/client_side_validations/

答案 1 :(得分:1)

如果您想在客户端进行此操作:

<script>
   $(document).ready(function(){
      $('#status').change(function(){
          if($(this).val() == "Closed" && ($('#amount').val() == null || $('#amount') == "")){
            alert("Amount must be needed when status is closed")
          }
        });
     });
</script>

答案 2 :(得分:0)

1)Javascript表单验证通常由名称完成。

 function ValidateForm(){
     var form = document.forms['myForm'];
     if ((form['status'].value == "Closed") && !(form['amount'].value)){
         alert("You gave a 'Closed' status value, but did not provide an amount, please rectify this problem!");
         return(false);
     } else {
        return(true);
     }
 }

然后:

         <%= simple_form_for @invoice, :onsubmit => "ValidateForm();", :html => { :class => 'form-horizontal', :name => 'myForm' } do |f| %>
         <%= f.input :amount, :html => { :name => 'amount'}, as: :string %>
         <%= f.input :status, as: :select, :html => { :name => 'status'}, collection: Invoice::VALID_STATUS %>

在提交表单时,但在实际发布到服务器之前,会触发一个简短的演练onSubmit

由事件触发并以return(false);终止的javascrtipt函数将立即终止事件,而return(true);(或其他任何其他事实)使事件按计划继续。

最后,要注意完全依赖客户端验证是一个糟糕的想法,因为一个坚定的用户可以做类似的事情:

1)使用萤火虫打开一个完全合法的提交并检查标题等 2)制作包含伪造/不良数据的自己的HTTP请求 3)通过任何一种无数的HTTP工具提交它。

Clientside Validation是一个“很高兴”。 Serverside验证是“必须拥有的”。