【问题标题】:How can I use a custom predicate to validate multiple fields with dry-validation?如何使用自定义谓词通过干验证来验证多个字段?
【发布时间】:2016-12-28 01:12:47
【问题描述】:

我有一个地址表单,我想对其进行整体验证,而不是单独验证每个输入。我只能通过将 line1、city、state、zip 传递给自定义谓词方法来判断地址是否有效,以便它可以将它们作为一个单元进行检查。

我该怎么做?我只看到如何验证单个字段。

【问题讨论】:

    标签: ruby-on-rails ruby validation


    【解决方案1】:

    看来this "High-level Rules" example 可以帮到你:

    schema = Dry::Validation.Schema do
      required(:barcode).maybe(:str?)
    
      required(:job_number).maybe(:int?)
    
      required(:sample_number).maybe(:int?)
    
      rule(barcode_only: [:barcode, :job_number, :sample_number]) do |barcode, job_num, sample_num|
        barcode.filled? > (job_num.none? & sample_num.none?)
      end
    end
    

    barcode_only 一次检查 3 个属性。

    所以你的代码可能是:

      rule(valid_address: [:line1, :city, :state, :zip]) do |line, city, state, zip|
        # some boolean logic based on line, city, state and zip
      end
    

    【讨论】:

    【解决方案2】:

    更新——这是针对 ActiveRecords 而不是 dry-validation gem。

    请参阅本教程,http://guides.rubyonrails.org/active_record_validations.html

    引用教程,

    您还可以创建验证模型状态的方法,并在它们无效时将消息添加到错误集合中。然后,您必须使用 validate (API) 类方法注册这些方法,并传入验证方法名称的符号。

    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
    

    【讨论】:

    • 很遗憾,您在这里指的是 ActiveRecord 验证,但我使用的是 github.com/dry-rb/dry-validation,所以这不是解决方案。
    • 天哪,对不起!
    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多