Search code examples
ruby-on-railsregexruby-on-rails-3grails-validation

Why my validation does not pass


I am developing Rails 3 app.

I would like to validate the "Cake" model's "size" attribute input field to only allow user to input +1,-1,+10,-10 and +25,-25, nothing else.

I use the following validation to validate "size":

class Cake < ActiveRecord::Base
  validates_format_of :size, :with => /^[-+]?(1|10|25)$/, :message=>'size not allowed.'
  ...

end

(The "size" attribute in my database "cakes" table is a "double" type.)

In the UI, I always get fail message of the validation even I input 1 or 10 or 25 or +1 or whatever. Why my validation does not pass even the value is right?


Solution

  • I'm not sure if validating an Integer with a Regex works.

    You could try validates_inclusion_of :size, :in=>[-1,+1,-10,+10,-25,+25], :message=>'size not allowed.'