我正在使用dry-type和dry-struct,我想进行条件验证。
针对课程:
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
我想将tax_ammount
验证为整数和强制性的 if 'tax_type =='IS'。
答案 0 :(得分:5)
dry-struct
实际上是用于基本类型声明和强制的。
如果您想进行更复杂的验证,那么您可能还想实现dry-validation
(如dry-rb
的建议)
请参阅Validating data with dry-struct,其中指出
请不要。结构应与有效输入配合使用,它不能生成足以向用户显示错误消息的错误消息。请使用dry-validation验证传入的数据,然后将其输出传递给结构。
使用dry-validation
的条件验证类似于
TaxValidation = Dry::Validation.Schema do
# Could be:
# required(:tax_type).filled(:str?,
# size?: 2..3,
# included_in?: %w(IVA IS NS))
# but since we are validating against a list of Strings I figured the rest was implied
required(:tax_type).filled(included_in?: %w(IVA IS NS))
optional(:tax_amount).maybe(:int?)
# rule name is of your choosing and will be used
# as the errors key (i just chose `tax_amount` for consistency)
rule(tax_amount:[:tax_type, :tax_amount]) do |tax_type, tax_amount|
tax_type.eql?('IS').then(tax_amount.filled?)
end
end
tax_type
进入%w(IVA IS NS)
列表; tax_amount
是可选的,但如果填写,则必须为Integer
(int?
);并且; tax_type == 'IS'
(eql?('IS')
),则必须填写tax_amount
(根据上述规则,它必须是Integer
)。很显然,您也可以验证您的其他输入,但是为了简洁起见,我省略了这些输入。
示例:
TaxValidation.({}).success?
#=> false
TaxValidation.({}).errors
# => {:tax_type=>["is missing"]}
TaxValidation.({tax_type: 'NO'}).errors
#=> {:tax_type=>["must be one of: IVA, IS, NS"]}
TaxValidation.({tax_type: 'NS'}).errors
#=> {}
TaxValidation.({tax_type: 'IS'}).errors
#=> {:tax_amount=>["must be filled"]}
TaxValidation.({tax_type: 'IS',tax_amount:'NO'}).errors
#=> {:tax_amount=>["must be an integer"]}
TaxValidation.({tax_type: 'NS',tax_amount:12}).errors
#=> {}
TaxValidation.({tax_type: 'NS',tax_amount:12}).success?
#=> true