Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Validating min and max length of a string but allowing it to be blank

I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

validates_length_of :foo, :maximum => 5 validates_length_of :foo, :minimum => 5 

How do I write this to accomplish my goal?

like image 888
bgadoci Avatar asked Dec 14 '10 17:12

bgadoci


2 Answers

You can also use this format:

validates :foo, length: {minimum: 5, maximum: 5}, allow_blank: true 

Or since your min and max are the same, the following will also work:

validates :foo, length: {is: 5}, allow_blank: true 
like image 95
quainjn Avatar answered Sep 27 '22 23:09

quainjn


I think it might need something like:

validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true 

More examples: ActiveRecord::Validations::ClassMethods

like image 34
DigitalRoss Avatar answered Sep 27 '22 22:09

DigitalRoss