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

Combinator for additional validation logic #37

Open k-bx opened 5 years ago

k-bx commented 5 years ago

Hi, sorry if I've missed this somehow in existing API.

I have this part of form which is only displayed if the "trafficking" checkbox is checked, so I need to validate its fields only then. I couldn't figure out how to do this without exporting the Validator(..) constructors for matching. Currently I did it like this:

ifTraffickingEnabled : Validator error { subject | trafficking : Bool } -> Validator error { subject | trafficking : Bool }
ifTraffickingEnabled validator =
    V.Validator
        (\subject ->
            if subject.trafficking then
                let
                    (V.Validator f) =
                        validator
                in
                f subject

            else
                []
        )

modelValidator : Validator ( Field, String ) Model
modelValidator =
  V.all
    [ ...
    , ifTraffickingEnabled (V.ifNothing .totalBudget ( TotalBudget, "Can't be empty" ))
    ]

Did I miss something? Thanks!