Conditional validation
Opened this issue · 6 comments
There is ifTrue : (subject -> Bool) -> error -> Validator error subject
to return a fixed error, when a predicate is not true.
I think it's a good idea to add a helper to have validation only in the case a predicate holds.
Example
- If the age of somebody is
>= 18
, the person has to be this tall (made up). - Different rules for different types of data
A helper would look like this example.
conditionalValidator : (a -> Bool) -> Validator e a -> Validator e a
conditionalValidator pred validator =
Validate.fromErrors <|
\value ->
if pred value then
Validate.validate validator value
else
[]
I like to make API decisions based on situations that have come up in practice.
Do you have any before/after examples of some code you've written that would have used this if it existed?
The code above is what I'm using right now. The examples above are comparable to the real use case: Validating form input. Depending on a dropdown field "type". If one specific value is selected a list in another field has to contain at least one value, otherwise it doesn't matter. This is one case, and there are more. One can try to model some of those cases via types, but I think the capabilities are limited in elm, without refinement types.
Perhaps there is a another, better solution? Happy to hear it :)
Sorry, to clarify - I'm looking for something really specific - not a hypothetical or comparable example, but rather the exact use case that came up in your application. 😄
So for example:
Depending on a dropdown field "type". If one specific value is selected a list in another field has to contain at least one value, otherwise it doesn't matter
What did the dropdown contain? What was the one specific value that was selected, and what was the other field that had to contain what value?
It's very important to me to understand the particulars of the motivating use case before making an API decision on this.
@rtfeldman Let's talk in elm slack
Having implemented this in another project in another language and coming back to this issue: Conditional could/should be possible using any
.
Example from top:
If the age of somebody is >= 18, the person has to be this tall (made up).
any(person.age < 18, person has to be this tall)