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

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

问题描述

如果我愿意

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

我仍然有可能使用包含以下内容的文本仅个空格 / r / n -不可见字符,虽然按定义文本不是空白,但通过查看它却是空白

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

我如何验证文本的最小和最大长度在上面列出并且也是可见的(不是10个空格)

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

推荐答案

Rails添加了方便的方法空白?,它按照中所述检查错误,零和空字符串在这里

Rails还添加了方便的验证器 allow_blank:false

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:

validate:body,状态: true,allow_blank:false

编辑(以上原始答案):

Edit (original answer above):

如下面的答案所述,不需要 allow_blank:false ,因为这是 presence的默认行为:正确

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天全站免登陆