Custom predicates in dry-schema

Hi there,

I am currently in the process of evalating using dry-schema for some input validation before hitting our ActiveRecord classes in a Rails application. Everything is working nice and smoothely. But now I wanted to add some custom predicates to match some of our application inputs. For example, we use prefixed-uuids for all of our objects and I want to validate with a Regex that only ids with a certain prefix can be passed in:

module CustomPredicates
  include Dry::Logic::Predicates

  def uuid_with_prefix?(prefix, input)
    input =~ /\A#{prefix}_[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\Z/
  end
end
class ApplicationSchema < Dry::Schema::JSON
  # here I would like to specify where the predicates are loaded from
end

The documentation says at one point that inheriting like this is possible, but that seems not to be correct. I have opened a GH issue about this. I am not too fixated on this, but it would be the nicest way to reuse logic.

class PostSchema < ApplicationSchema
  required(:text).filled(:string?)
  required(:author).filled(:string?, uuid_with_prefix?: 'user')
end

I have tried all different method of how to specify predicates that are documented in the other gems like confgure { config.predicates = CustomPredicates } but I suspect that in dry-schema I somehow need access to the PredicateRegistry but it is not exposed anywhere.

Is there maybe something still missing, that this cannot be done yet? Should I better stick with the old version of dry-validation until the extraction process is done? Or am I completely missing something?

If somebody points me into the right direction, I would be totally happy to contribute a section of the readme that describes how to do this.

Hey,

Custom predicates will not be supported in dry-schema. The alternative is as simple as defining methods on validation contracts, which will be available in dry-validation 1.0.0. I already started working on it and we could have an early alpha/beta ready later this month, if there’s interest in testing it early.

Cheers!

Ok, so for now, I will work with the current version of dry-validation

Hi, @solnic . I’m in a similar situation. I’ve inherited a legacy app that has custom predicates, similar to above. I have no prior little dry-validation experience, but have been learning a lot in the past few days as we address vulnerability concerns by updating gems, including dry-validation from 0.13 to 1.x.

You suggest, “defining methods on validation contracts.” I’ve not been able to find references on what that looks like, based on that name. I’ve been all up and down the dry-validation 1.7 docs and have not found any examples of writing a custom validation method when simple type/value checks are insufficient.

Can you share an example of what that looks like, or link to current docs that describe this?

Take a look at contract macros. Either that, or just rewriting as rules

1 Like