John Fadria
John Fadria

Reputation: 1945

Validates numericality only if presence (if user fill it), doesn't work

I follow some tips to validates the numericality of a field only if presence, with:

validates_numericality_of :year, only_integer: true, allow_nil: true

or

validates_numericality_of :year, only_integer: true, allow_blank: true

But I can create it with a year like 'asdfasdf' and rails stores a blank year.

What can be wrong?

Upvotes: 4

Views: 2446

Answers (2)

As said in api dock, validates_numericality_of validates whether the value of the specified attribute is numeric by trying to convert it to a float with Kernel.Float (if only_integer is false) or applying it to the regular expression /\A[+-]?\d+\Z/ (if only_integer is set to true).

That's why in your case it doesn't fail, because the 'asdfasdf' string is "converted to an integer".

If you remove allow_nil then it won't allow to store nil values an it will fail:

validates_numericality_of :year, only_integer: true

If you want it to fail but still allow nil values, you can always use a before_validate filter and make it fail there.

Upvotes: 1

PJ Bergeron
PJ Bergeron

Reputation: 2998

Instead of allow_nil: true, use allow_blank: true.

You should also replace text_field by number_field in your view. With number_field, if your characters are not only digits, it's evaluated as nil.

Upvotes: 6

Related Questions