rtfeldman / elm-validate

Convenience functions for validating Elm data.
http://package.elm-lang.org/packages/rtfeldman/elm-validate/latest
BSD 3-Clause "New" or "Revised" License
145 stars 28 forks source link

Conditional validation #24

Open andys8 opened 6 years ago

andys8 commented 6 years ago

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

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
                []
rtfeldman commented 6 years ago

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?

andys8 commented 6 years ago

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

rtfeldman commented 6 years ago

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.

andys8 commented 6 years ago

@rtfeldman Let's talk in elm slack

k-bx commented 5 years ago

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

andys8 commented 5 years ago

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)