最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validation before saving Rails - Stack Overflow

programmeradmin1浏览0评论

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

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

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

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

Share Improve this question edited Jan 27, 2013 at 18:22 Abraham P 15.5k13 gold badges63 silver badges130 bronze badges asked Jan 27, 2013 at 18:19 zurikzurik 5131 gold badge8 silver badges22 bronze badges 2
  • Do you want to do this server side, after the form is posted, or client side, before posting the form? (Really, the right answer is both, but what is your question?) – Abraham P Commented Jan 27, 2013 at 18:24
  • Is jQuery ok or does it have to be raw javascript? Are you in control of the javascript libraries/plugins that you use? – Abraham P Commented Jan 27, 2013 at 18:32
Add a ment  | 

3 Answers 3

Reset to default 3

In the model (app/models/invoice_model.rb) put

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./bcardarella/client_side_validations/

1) Javascript Form Validation is generally done by names.

 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.

A javascrtipt function that is trigered by an event and terminates with return(false); will immediately terminate the event, while 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.
2) Craft their own HTTP request containing bogus/bad data.
3) Submit it through any one of the myriad HTTP tools.

Clientside Validation is a "nice to have". Serverside Validation is a "must have".

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>
发布评论

评论列表(0)

  1. 暂无评论