Extend Akkurate
Although Akkurate focuses on providing all the essential constraints, you might need to write your own constraints for custom business validation.
Inline constraints
Sometimes you might need a constraint for only one specific case across the whole codebase; this is where inline constraints shine. To create one, use constrain
inside your validator:
The constrain
function accepts a lambda, which must return a Boolean
; if true
, the constraint is satisfied; otherwise a violation is raised.
Named constraints
If the same constraint is used multiple times, stop repeating yourself and extract it to an extension function.
Let's reuse our previous example, extract the constraint to an extension function with a Validatable<String>
receiver, and name it hasWordCountGreaterThanTwo
:
However, named constraints can do more than inline ones. First, we can add a parameter to count a variable number of words:
You can also add a default message to explain what happened, in case the developer using your constraint doesn't provide one:
Finally, it might be useful to support nullable values like in Akkurate's built-in constraints. The constrainIfNotNull
function can be used to create constraints that are always satisfied when the value is null
(like described by the Vacuous Truth principle):
Test your code
When writing your own constraints, you might want to write unit tests to verify their behaviors.
This is done by installing a new artifact:
Install akkurate-test
This artifact provides the Validatable function, which returns a value ready to be constrained: