【发布时间】:2018-03-29 22:30:56
【问题描述】:
我创建了一个简单的银行应用程序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 %>
模型.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 种类型的验证,但它对我不起作用,所以任何人都可以帮助我:)
【问题讨论】:
-
大概您的
balance字段是一个数字,因此您需要通过数字比较而不是字符串来验证这一点。您是否尝试过将in: 0..1e9作为一个良好范围的示例? -
我尝试了 1 到 9999 的范围,但它不起作用。
标签: javascript ruby validation ruby-on-rails-4 model-view-controller