busypeoples / spected

Validation library
MIT License
703 stars 32 forks source link

Enhancement Request: Simulated Value #95

Closed AutoSponge closed 6 years ago

AutoSponge commented 6 years ago

For history, see https://github.com/25th-floor/revalidation/pull/50, look for "simulated value"

Goal: validate(success, fail, spec, input) where input can be a function that takes key.

Usage: Would be used to execute validation against a spec with a given input object while transforming/substituting/simulating a single value. This could answer simple questions like "if this value were empty, would that return an error".

Internals: when input is a function, the value should be determined by input(key) instead of input[key]. The function in our use case would need to return the input object with the simulated value replaced for the actual value. Shallow example: key => ({...input, [key]: ''})

Changes: looks like a signature change to validate and runPredicate. Should be non-breaking.

AutoSponge commented 6 years ago

If this is a feature you want, I can work on a PR this week. If not, I'll close if there's another pattern that will accomplish the same thing.

busypeoples commented 6 years ago

Sorry @AutoSponge for not getting back to you earlier on! I will have a look at the problem.

busypeoples commented 6 years ago

Took a look at the problem. Not sure if just calling input(key) would suffice, as all still needs an object. If input is a function, where does the object come from? key => key ? ({...input, [key]: ''}) : input like this?

Might not even need to make any changes to runPredicate, actually.

AutoSponge commented 6 years ago

@busypeoples It's been a while, so I may have to revisit this, but as I remember, I wanted to pass a "proxy object" to validate which could evaluate the correct input state with one property (key) changed to an empty string. This would have the effect of asking validate, "If I delete this value, will that make the field invalid?"

I know it's a different way to think about validation, we usually only consider it after something changes. But in this case, the question "given all other current values, would this field's value be required?" is difficult to answer without changing the context object.

If you think it's worth a shot, I can put together a PR for this. If my original analysis was correct, it won't be a breaking change, just an overloaded signature for validate.

busypeoples commented 6 years ago

@AutoSponge Thanks! That would be great if you could create a PR. Also don't think there would be a breaking change.

busypeoples commented 6 years ago

Thanks @AutoSponge merged your PR.