How to validate text isn't blank in Rails

泪湿孤枕 提交于 2019-11-29 01:06:29

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.

Jacob Minshall

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.

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!