我有一个地址表单,我想作为一个整体验证,而不是自己验证每个输入.我只能通过将line1,city,state,zip传递给自定义谓词方法来判断地址是否有效,以便它可以将它们作为一个单元进行检查.
我怎样才能做到这一点?我只看到如何验证单个字段.
最佳答案
更新 – 这适用于ActiveRecords而不是干验证gem.
请参阅本教程,http://guides.rubyonrails.org/active_record_validations.html
引用教程,
You can also create methods that verify the state of your models and add messages to the errors collection when they are invalid. You must then register these methods by using the
validate
(API) class method, passing in the symbols for the validation methods’ names.
class Invoice < ApplicationRecord
validate :discount_cannot_be_greater_than_total_value
def discount_cannot_be_greater_than_total_value
if discount > total_value
errors.add(:discount, "can't be greater than total value")
end
end
end
相关文章
- ruby-on-rails - 使用before_save回调或自定义验证器添加验证错误?
- ruby-on-rails - 如何验证来自许多人的一个字段的存在
- ruby-on-rails - 在Rails应用程序中添加其他字段(通过验证)来设计视图/模型
- 如何在自定义验证方法中使用现有的Rails验证器?
- ruby-on-rails - 对Rails中的几个字段进行相同的自定义验证
- ruby-on-rails - 如何使用设计验证来验证注册电子邮件地址是否来自某个域?
- ruby-on-rails - Rails 3使用自定义消息验证许多列的存在
- ruby-on-rails - 通过Ruby on Rails验证方法验证年份的最佳方法?