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

I think it might need something like:

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

More examples: ActiveRecord::Validations::ClassMethods


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

Or even more concise (with the new hash syntax), from the validates documentation:

validates :foo, length: 5..5, allow_blank: true

The upper limit should probably represent somehting more meaningful like "in: 5..20", but just answering the question to the letter.