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

Allow reusing validators #17

Open zwilias opened 6 years ago

zwilias commented 6 years ago

Some sort of contravariant map would allow reusing validators in different contexts.

Possible names, with input from @norpan and @gyzerok on slack:

I sort of like select, though I'd already typed it out with preMap and figured a PR was a better place for discussion.

One alternative is to encourage users to write Sometype -> Validator Error Sometype style functions instead. I feel like that sort of defeats the purpose of providing a nice type for a validator, though.

gyzerok commented 6 years ago

This issue comes from the discussion in Slack.

In my project we are using elm-validate and after recent update it appeared to be impossible to use it in a samish way. I will post here our use-case, so you will have more information for API design.

On our forms we need to be able to do validation dynamically. It means that we don't show all the errors once user clicks submit, but show them as user goes through the form.

With previous implementation we had following code

validateFoo : foo -> List ValidationError
...

validateModel : Model -> List ValidationError
validateModel =
    Validate.all [ .foo >> validateFoo ]

This way we are able use validator both for validating specific field and for validating entire model. With the new API it is impossible to do so anyhow.

gyzerok commented 6 years ago

Since original discussion in Slack, one more naming idea popped up in my head - narrow. Example:

validateModel =
    Validate.all [ Validate.narrow .foo validateFoo ]
andys8 commented 6 years ago

With this PR one could compose validatorA and validatorB to create validatorModel, right?

type alias Model = { a: A, b: B }

validatorA: Validator a A
validatorB: Validator a B
validatorModel : Validator a Model

I need this! :smiley: :+1:

rtfeldman commented 6 years ago

How about by as a name?

userValidator : Validator String User
userValidator =
    Validate.by .username usernameValidator

cc @gyzerok @zwilias

andys8 commented 6 years ago

For the naming, the functionality can probably be compared to lenses (focus / optics), but only one direction is necessary. Or transformation. But naming is different in Elm, I know. I think you will make a good decision and I'm looking forward for the feature.

https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/basic-lensing

https://en.m.wikipedia.org/wiki/Bidirectional_transformation

andys8 commented 4 years ago

Still missing this feature. Going to look for other libraries.