How can I use my own predicate to test multiple fields with dry validation?

I have an address form that I want to verify as a whole, and not independently verify each entry. I can only say if the address is valid by passing string1, city, state, zip to the proprietary predicate method so that it can check them as a unit.

How can i do this? I only see how to check individual fields.

+4
source share
2 answers

The update is for ActiveRecords, not dry-validationgem.

See this tutorial, http://guides.rubyonrails.org/active_record_validations.html

Quote from a textbook,

, , . 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
+1

, " " :

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
+1

Source: https://habr.com/ru/post/1665054/


All Articles