简体   繁体   English

保存Rails之前的验证

[英]Validation before saving Rails

I would like to carry out a validation before saving by determining if a User has filled in a particular field, the Payment amount field below and chosen status = "Closed" before submitting the form. 我想在保存之前进行一次验证,方法是确定用户是否填写了特定字段,下面的付款金额字段并且在提交表单之前选择了状态=“已关闭”。 If he does one without the other then the form should not save 如果他在没有其他人的情况下做某事,则该表格不应保存

Edit page 编辑页面

<%= 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 %>

VALID_STATUS = [ 'Draft', 'Open', 'Closed', 'Void' ] in Invoice.rb VALID_STATUS = [Invoice.rb中的'Draft','Open','Closed','Void']

I would like that if the user changes the Status to Closed he should have entered an amount in the form. 我希望如果用户将“状态”更改为“已关闭”,那么他应该在表格中输入金额。 A user should not be able to change status to closed without entering an amount 用户在不输入金额的情况下不能将状态更改为已关闭

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

validate :close_must_have_amount

Then define it (same file) 然后定义它(相同文件)

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

To have the model level validations applied client side you can use 要在客户端应用模型级别验证,您可以使用
https://github.com/bcardarella/client_side_validations/ https://github.com/bcardarella/client_side_validations/

If you want to do it in client side: 如果要在客户端执行此操作:

<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>

1) Javascript Form Validation is generally done by names. 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);
     }
 }

And then: 接着:

         <%= 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 %>

A brief walkthrough onSubmit triggers when a form is submitted, but before it is actually posted to the server. 简短的演练onSubmit会在提交表单时(但实际上未将其发布到服务器之前)触发。

A javascrtipt function that is trigered by an event and terminates with return(false); 一个由事件触发并以return(false);终止的javascrtipt函数return(false); will immediately terminate the event, while return(true); 将立即终止事件,而return(true); (or pretty much anything else really) makes the event continue as planned. (或几乎所有其他内容)使活动按计划进行。

Finally, be aware that relying exclusively on client side validation is a terrible idea, as a determined user could do something like: 最后,请注意,完全依靠客户端验证是一个糟糕的主意,因为确定的用户可以执行以下操作:

1) Make a perfectly legitimate submission with firebug open and inspect the headers etc. 1)打开萤火虫,进行完全合法的提交并检查标题等。
2) Craft their own HTTP request containing bogus/bad data. 2)制作自己的包含伪造/不良数据的HTTP请求。
3) Submit it through any one of the myriad HTTP tools. 3)通过多种HTTP工具之一提交它。

Clientside Validation is a "nice to have". 客户端验证是一个“不错的选择”。 Serverside Validation is a "must have". 服务器端验证是“必须具备”的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM