如何验证文本在 Rails 中不是空白的 [英] How to validate text isn't blank in Rails

查看:9
本文介绍了如何验证文本在 Rails 中不是空白的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

解决方案

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.

这篇关于如何验证文本在 Rails 中不是空白的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆