本文介绍了轨道非必填项ActiveRecord的正则表达式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证与正则表达式的一个字段,也允许它为空(接受一个空字符串)。到目前为止,我所管理的唯一一件事就是写一个正则表达式,它允许一个空字符串,如:

I'd like to validate a field with regex and also allow it to be blank (to accept an empty string). So far, the only thing I managed is to write a regex that allows an empty string, like:

validates :field,
          format: { with: /\A([a-z]+|)\z/i }

现在,这不可能是一个正确的方式 - 这似乎是一个丑陋的黑客攻击。我想知道是否有另一种(正确)的做法?

Now, this can't be a proper way - this seems like an ugly hack. I'd like to know if there's another (proper) approach?

推荐答案

allow_blank 应工作。 (也有 allow_nil 只接受零值(不是空字符串))

allow_blank should work. (There is also allow_nil for accepting nil values only (not an empty string))

validates :field,
          format: { with: /\A([a-z]+|)\z/i }, :allow_blank => true

这篇关于轨道非必填项ActiveRecord的正则表达式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 09:50