Rails: How to validate format only if value is present?

后端 未结 2 1123
鱼传尺愫
鱼传尺愫 2021-02-06 21:29

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:

相关标签:
2条回答
  • 2021-02-06 22:09

    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

    0 讨论(0)
  • 2021-02-06 22:16

    Add unless nil? || blank?, which should skip the validation if it's blank (empty) or nil, I believe.

    See the last code example on this page.

    0 讨论(0)
提交回复
热议问题