简体   繁体   English

如何判断表格输入值是否为数字?

[英]How can I judge whether if form input value is number or not?

I'd like to proceed transaction when params[:points] is not a number. params[:points]不是数字时,我想进行transaction I coded like this. 我这样编码。

if params[:points] !=~ /^[+-]?\d+$/
  transaction
end

However, it proceeds transaction even when I input abcdefh into params[:points] . 但是,即使我将abcdefh输入到params[:points] ,它也会继续进行transaction How can I fix? 我该如何解决?

All values received from a form are Strings. 从表单接收的所有值都是字符串。 Some might look like a numeric value, but they'll remain strings until you explicitly convert them to an integer, which you can do using String's to_i method. 有些可能看起来像数字值,但它们将保留为字符串,直到您将其显式转换为整数为止,您可以使用String的to_i方法进行此操作。

You can check to see if the entire value contains digits, which is a good clue that it's truly a number using something like: 您可以使用以下方法检查整个值是否包含数字,这可以很好地表明它确实是数字:

!!params[:points][/^[+-]?\d+$/]

to return true/false if it's a string version of a number. 如果它是数字的字符串版本,则返回true / false。

'012345'[/^[+-]?\d+$/]
=> "012345"

!!'012345'[/^[+-]?\d+$/]
=> true

'+012345'[/^[+-]?\d+$/]
=> "+012345"

!!'+012345'[/^[+-]?\d+$/]
=> true

'-+012345'[/^[+-]?\d+$/]
=> nil

!!'-012345'[/^[+-]?\d+$/]
=> true

'0 foo'[/^[+-]?\d+$/]
=> nil

!!'0 foo'[/^[+-]?\d+$/]
=> false

I think you want .match , not !=~ . 我认为您想要.match ,而不是!=~

unless params[:points].match(/^[+-]?\d+$/)
  #stuff
end

Alternatively, I finally figured out that the 'does not match' operator exists, it's just that it's !~ , not !=~ . 或者,我最终发现存在“不匹配”运算符,只是!~而不是!=~ So yeah, taking out that equals sign should also solve your problem. 是的,去掉等号也可以解决您的问题。

Maybe you are confused by your own logic. 也许您对自己的逻辑感到困惑。

  • params[:points] is "abcdefh" params[:points]"abcdefh"
  • params[:points] !=~ /^[+-]?\\d+$/ params[:points] !=~ /^[+-]?\\d+$/
  • transaction is executed →执行transaction

On the other hand, 另一方面,

I'd like to proceed transaction when params[:points] is not a number 我想在params [:points]不是数字时继续进行交易

That is exactly the case. 确实是这样。 Nothing is wrong. 没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM