I'm using dry-types and dry-struct and I would like to have a conditional validation.
for the class:
class Tax < Dry::Struct
attribute :tax_type, Types::String.constrained(min_size: 2, max_size: 3, included_in: %w[IVA IS NS])
attribute :tax_country_region, Types::String.constrained(max_size: 5)
attribute :tax_code, Types::String.constrained(max_size: 10)
attribute :description, Types::String.constrained(max_size: 255)
attribute :tax_percentage, Types::Integer
attribute :tax_ammount, Types::Integer.optional
end
I want to validate tax_ammount
as an Integer and mandatory if `tax_type == 'IS'.
dry-struct
is really for basic type assertion and coercion.If you want more complex validation then you probably want to implement
dry-validation
as well (as recommended bydry-rb
)See Validating data with dry-struct which states
The conditional validation using
dry-validation
would be something liketax_type
to be in the%w(IVA IS NS)
list;tax_amount
to be optional but if it is filled in it must be anInteger
(int?
) and;tax_type == 'IS'
(eql?('IS')
) thentax_amount
must be filled in (which means it must be anInteger
based on the rule above).Obviously you can validate your other inputs as well but I left these out for the sake of brevity.
Examples: