Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
John Fadria Avatar asked Mar 17 '23 20:03

John Fadria


1 Answers

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.

like image 124
PJ Bergeron Avatar answered Apr 08 '23 12:04

PJ Bergeron