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

Allow reusing validators

Open zwilias opened this issue 7 years ago • 6 comments

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

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

  • preMap
  • comap
  • contraMap (not used in Elm, so far)
  • select (i.e. Validate.select .name nameValidator)

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.

zwilias avatar Feb 07 '18 13:02 zwilias

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 avatar Feb 07 '18 13:02 gyzerok

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

validateModel =
    Validate.all [ Validate.narrow .foo validateFoo ]

gyzerok avatar Feb 07 '18 17:02 gyzerok

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:

andys8 avatar Jul 19 '18 15:07 andys8

How about by as a name?

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

cc @gyzerok @zwilias

rtfeldman avatar Jul 19 '18 17:07 rtfeldman

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

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

andys8 avatar Nov 21 '19 22:11 andys8