35

if I do

  validates :body, :presence => true, :length => {:maximum => 30000, :message => ' is a bit long...'}
  validates :body, :length => {:minimum => 10, :message => ' is a bit short...'}

I still have a possibility of having a text which includes only spaces and /r or /n - non visible chars, which while the text isn't blank by definition, it is blank by looking at it

How can I validate that the text had a min and max length listed above and is also visible (not 10 spaces)

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • You could always try using regex to check for non-word, non-numerical, and special characters, kind of like what was suggested in this other [question/answer](http://stackoverflow.com/questions/7680771/rails-custom-validation-based-on-a-regex). – summea Mar 18 '13 at 16:57
  • Try looking at this [question/answer](http://stackoverflow.com/questions/6765020/regex-to-validate-string-having-only-characters-not-special-characters-blank) as well. – summea Mar 18 '13 at 18:30

3 Answers3

72

Rails adds the handy method blank? which checks for false, nil and empty strings as described here.
Rails also adds the handy validator allow_blank: false.

So in your case it should be:

validates :body, presence: true, allow_blank: false


Edit (original answer above):

As stated in the answer below, allow_blank: false is not needed as that's the default behaviour of presence: true.

Lisinge
  • 2,017
  • 2
  • 27
  • 44
  • 7
    Setting `allow_blank: false` is superfluous since `validates presence: true` already does what you want. Please note the correct answer at the bottom: http://stackoverflow.com/a/24832913/273715 – jottr Sep 25 '14 at 18:04
32

presence: true already does that according to http://guides.rubyonrails.org/active_record_validations.html#presence

This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

jottr
  • 3,256
  • 3
  • 29
  • 35
Jacob Minshall
  • 1,044
  • 9
  • 15
  • This is the same for Rails 3: http://guides.rubyonrails.org/v2.3.11/activerecord_validations_callbacks.html#validates-presence-of – jottr Sep 25 '14 at 17:58
6

What if you try adding something like this:

validates_format_of :body, :with => /\A[[:graph:]]\Z/i

Notes:

  • validates_format_of lets you validate with regex
  • [[:graph:]] lets you check a string for printable characters (see "Character Classes")
summea
  • 7,390
  • 4
  • 32
  • 48