-1

我創建了一個簡單的銀行應用程序This is the Link用於學習目的。所有的功能是迷人的工作,但我要檢查驗證,如果用戶輸入負值,如-100,所以它顯示錯誤或警報消息。那麼如何執行。我想驗證一個文本框檢查負值像-100?

感謝提前:)

_form.html.erb

<%= form_for(@depositemoney) do |f| %> 
    <% if @depositemoney.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@depositemoney.errors.count, "error") %> prohibited this depositemoney from being saved:</h2> 

     <ul> 
     <% @depositemoney.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :balance %><br> 
    <%= f.number_field :balance %> 
    </div> 
    <%= f.hidden_field :u_id, :value => current_user.id %> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

Model.rb

class Depositemoney < ActiveRecord::Base 
     # validates :balance, :numericality => {:only_integer => true} 
     # validates :balance, presence: true 
      validates :balance, presence: true 
       # validates :balance, :inclusion => {:in => [1,2]} 
      validates :balance, format: { with: /\A\d+\z/, message: "Integer only. No sign allowed." } 
end 

我嘗試驗證的3種類型,但它不worrk對我來說,任何人都可以幫助我:)

+1

想必你'balance'場是一個數字,所以你要驗證與數值的比較,而不是字符串。你有沒有試過':0..1e9'作爲一個好範圍的例子? – tadman

+0

我試過了1至9999的響鈴,但它不起作用。 –

回答

1

:greater_than:greater_than_or_equal_to選項就是這樣。

class Hoge < ApplicationRecord 
    validates :balance, numericality: { greater_than: 0 } 
end 

它的工作原理如下圖所示:

Loading development environment (Rails 5.1.4) 
[1] pry(main)> Hoge.create(balance: 1) 
    (0.6ms) SET NAMES utf8mb4 COLLATE utf8mb4_general_ci, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483 
    (0.1ms) BEGIN 
    SQL (12.2ms) INSERT INTO `hoges` (`balance`, `created_at`, `updated_at`) VALUES (1, '2017-10-18 06:06:18', '2017-10-18 06:06:18') 
    (11.1ms) COMMIT 


    [2] pry(main)> Hoge.create(balance: -1) 
    (0.2ms) BEGIN 
    (0.2ms) ROLLBACK 
=> #<Hoge:0x007fa212e1cd80 id: nil, balance: -1, created_at: nil, updated_at: nil> 
[4] pry(main)> Hoge.create(balance: -1).errors 
    (0.3ms) BEGIN 
    (0.2ms) ROLLBACK 
=> #<ActiveModel::Errors:0x007fa20fcc37c0 
@base=#<Hoge:0x007fa20f6c08f0 id: nil, balance: -1, created_at: nil, updated_at: nil>, 
@details={:balance=>[{:error=>:greater_than, :value=>-1, :count=>0}]}, 
@messages={:balance=>["must be greater than 0"]}> 

FYI:http://guides.rubyonrails.org/active_record_validations.html