我想验证文本框以检查负值如-100?

时间:2017-10-18 05:49:55

标签: javascript ruby validation ruby-on-rails-4 model-view-controller

我创建了一个简单的银行应用程序This is the Link用于研究目的。如果用户输入-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种类型的验证,但它对我来说不起作用,所以任何人都可以帮助我:)

1 个答案:

答案 0 :(得分: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"]}>

仅供参考:http://guides.rubyonrails.org/active_record_validations.html

相关问题