1

フォームを送信する前に、ユーザーが特定のフィールド、下の[支払い金額]フィールドに入力し、ステータス= "Closed"を選択したかどうかを判断して、保存する前に検証を実行したいと思います。彼が一方を他方なしで行う場合、フォームは保存されるべきではありません

ページを編集

<%= 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=['ドラフト'、'オープン'、'クローズ'、'ボイド']

ユーザーがステータスをクローズに変更した場合、フォームに金額を入力する必要があります。ユーザーは、金額を入力せずにステータスをクローズに変更できないようにする必要があります

4

3 に答える 3

2

モデルに(app/models/invoice_model.rb)入れます

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/を使用できます。

于 2013-01-27T18:22:30.963 に答える
1

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フォームが送信されたとき、ただし実際にサーバーに投稿される前に、簡単なウォークスルーがトリガーされます。

イベントによってトリガーされて終了するjavascrtipt関数は、イベントreturn(false);をすぐに終了しますが、return(true);(または実際にはほとんど何でも)イベントを計画どおりに続行します。

最後に、決定されたユーザーは次のようなことを行う可能性があるため、クライアント側の検証のみに依存することはひどい考えであることに注意してください。

1)firebugを開いて完全に正当な送信を行い、ヘッダーなどを検査し
ます。2)偽の/不正なデータを含む独自のHTTPリクエストを作成します。
3)無数のHTTPツールのいずれかを介して送信します。

クライアントサイドの検証は「持っておくと便利」です。サーバーサイド検証は「必須」です。

于 2013-01-27T18:37:03.073 に答える
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>
于 2013-01-27T18:38:48.460 に答える