简体   繁体   中英

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. I coded like this.

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

However, it proceeds transaction even when I input abcdefh into params[:points] . 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.

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.

'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 !=~ .

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] !=~ /^[+-]?\\d+$/
  • transaction is executed

On the other hand,

I'd like to proceed transaction when params[:points] is not a number

That is exactly the case. Nothing is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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