elm-validate icon indicating copy to clipboard operation
elm-validate copied to clipboard

Conditional validation

Open andys8 opened this issue 7 years ago • 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
                []

andys8 avatar Jul 19 '18 16:07 andys8

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?

rtfeldman avatar Jul 19 '18 17:07 rtfeldman

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 :)

andys8 avatar Jul 19 '18 17:07 andys8

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 avatar Jul 19 '18 18:07 rtfeldman

@rtfeldman Let's talk in elm slack

andys8 avatar Jul 19 '18 19:07 andys8

Possibly related: https://github.com/rtfeldman/elm-validate/issues/37

k-bx avatar Dec 27 '18 16:12 k-bx

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)

andys8 avatar Dec 28 '18 21:12 andys8