Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shortcut for withValidation #117

Open
pke opened this issue Nov 7, 2019 · 3 comments
Open

Shortcut for withValidation #117

pke opened this issue Nov 7, 2019 · 3 comments

Comments

@pke
Copy link

pke commented Nov 7, 2019

🚀 Feature request

Current Behavior

Multiple validation are somewhat verbose to write for custom types:

const Efficiency = withValidate(NumberFromString, 
  (u,c) =>
    either.chain(
      NumberFromString.validate(u,c),
      n => {
        if (n <= 0) {
          return t.failure(u, c, `${n}% is not effcient enough and will not heat water.`)
        } else if(n >= 100) {
          return t.failure(u, c, `${n}% efficiency is against the laws of physics`)
        }
        return t.success(n)
      }
    )
)

Desired Behavior

const Efficiency = withValidate(NumberFromString,
  (u,c) =>
    pipe(
      NumberFromString.validate(u,c),
      validate(n => n > 0 || `${n}% is not effcient enough and will not heat water.`)(u,c),
      validate(n => n < 100 || `${n}% efficiency is against the laws of physics`)(u,c)
    )
)

Suggested Solution

My solution with pipe and this implementation of validate

const validate = f => (u, c) => n => {
  const invalid = f(n)
  return invalid ? t.failure(u, c, invalid) : t.success(n)
}

It does not work though as pipe is complaining about incompatible args.
It would also be nice to get rid of the NumberFromString.validate call, and make this somehow implicit.

Being new to FP I am lost here.

Who does this impact? Who is this for?

It would benefit advanced users I guess.

@gcanti gcanti transferred this issue from gcanti/io-ts Nov 7, 2019
@gcanti
Copy link
Owner

gcanti commented Nov 7, 2019

Note that using withValidate like this raises a problem: is and decode are not coherent

console.log(Efficiency.is(-10)) // true

@pke
Copy link
Author

pke commented Nov 7, 2019

Hmm... and what would be the solution to make this work? It should be a guard or something?

@steida
Copy link

steida commented Dec 7, 2019

@pke I would use t.intersection and show only the first error.

const NonEmptyTrimmedStringMax5 = t.intersection([
  // For 'Invalid string.' message.
  String,
  NonEmptyString,
  Trimmed,
  Max5,
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants