Rails:如何仅在存在值时验证格式? [英] Rails: How to validate format only if value is present?
问题描述
我想验证表单值的格式,允许空值或需要特定格式.
I would like to validate the format of a form value, allowing an empty value or requiring a specific format.
要根据格式验证值,这可以正常工作:
To validate a value against a format, this works fine:
validates :application_bundle_identifier, :format => {
:with => /^[a-zA-Z0-9.-]+$/,
:message => "A bundle identifier should contain only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters."
}
现在,我想允许用户根本不输入该值.在这种情况下,我可以将正则表达式调整为 ^[a-zA-Z0-9.-]*$
,但这似乎不是一个很好的 Rails 方式.根据格式的不同,这可能是不可能的,或者至少不太清楚.
Now, I would like to allow users to not enter the value at all. In this case, I could tweak the regexp to ^[a-zA-Z0-9.-]*$
, but this does not seem a very good Rails-way. Depending of the format, it might be not possible, or at least less clear.
这种情况下的最佳做法是什么?
What is the best practice in this case?
推荐答案
当属性为空/空/nil 时,您可以使用选项allow_blank: true
跳过验证.
You can use the option allow_blank: true
to skip the validation when the attribute is blank/empty/nil.
https://guides.rubyonrails.org/active_record_validations.html#allow-blank
这篇关于Rails:如何仅在存在值时验证格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!