0

我正在尝试验证用户在金额字段中输入的内容。

该字段是amount_money

此字段是在表单提交时验证的字符串

 monetize :amount, :as => :amount_money
 validates :amount, numericality: {only_integer: true}
 validates :amount_money, numericality: {greater_than_or_equal_to: 0}
 validate :amount_money_within_limit
 validate :is_a_valid_number

我想确保没有字母或符号,并且金额在可接受的范围内。

这样做的代码是

def amount_money_within_limit
    if amount_money && amount_money.cents > 10_000_00 
        errors.add(:amount_money, 'cannot exceed $10,000.')
    end
    if amount_money && amount_money.cents < 1_00 
      errors.add(:amount_money, 'Problem with Amount')
    end
end

这适用于输入数字,数字和字母,字母,特殊字符,但是

如果我尝试 Bob - 验证开始,但如果我尝试 BBob - 验证被绕过。

如果输入包含 2 个彼此相邻的大写字母 - 它会失败。我尝试了一个小写字母 - 但这不适合该领域是货币化的(金钱宝石) - 如果有有效的输入,小写字母就会出错。

如果该字段的输入包含两个大写字母 - 所有验证都被绕过 所以像 AA 这样的东西不会被上述验证中的任何东西捕获

4

2 回答 2

1

似乎您在错误的字段上放置了 1 个验证,您应该只在amount字段(您的真实数据库字段)上放置验证,而不是在gemamount_money的自动字段上。rails-money我会将他们关于数值验证的文档应用于您的案例:

monetize :amount,
  :numericality => {
    :only_integer => true,
    :greater_than_or_equal_to => 1_00,
    :less_than_or_equal_to => 10_000_00
  }

使用此设置,您不需要任何其他自定义验证。

于 2015-09-12T19:17:47.890 回答
1

为什么不使用正则表达式?像这样的东西:

def is_a_valid_number? amount_money
  amount_money =~ /\d+/
end
于 2015-09-12T16:56:26.373 回答