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

Allow undefined context, or a set a default context within the schema #440

Closed
kdschaffe opened this issue Feb 1, 2019 · 2 comments
Closed

Comments

@kdschaffe
Copy link

kdschaffe commented Feb 1, 2019

I found that when a schema uses context,

.when('$other', (other, schema) => (other === 4 ? schema.max(6) : schema)),

and a context isn't provided with schema.validate(), an error will occur:

TypeError: Cannot read property 'other' of undefined

Is there a way to avoid this error, without passing a context into the validate call?

A couple ideas:

  1. Set a default context at the schema level
  2. Allow an undefined context (not required to pass a context). Maybe internally, context would default to an empty object, and if context values aren't set, they simply get passed to schema rules as undefined. Rules can then handle this as needed.

For reference, this Formik issue might be resolved for some people by making this change in yup: jaredpalmer/formik#503. Although, I think resolving both issues would be beneficial.

@jquense
Copy link
Owner

jquense commented Feb 1, 2019

idk this sounds like good error, albeit not a super clear one. If you define a schema a dependent on context doesn't it make sense to error if you don't provide any context?

@kdschaffe
Copy link
Author

Thanks for the quick response. In general I think the error is fine. I'm interested in a way to allow the schema to decide wether it should error or not, though. Maybe you want yup to error by default, so option 2 isn't ideal.

Option 1 would allow the schema to have individual rules handle undefined context, or undefined properties on context, or even better, avoid undefined values altogether. This would help in situations where validation and casting logic is handled by a base class, or wrapper, where most of the time you can use the default context but can overwrite validation/casting and provide a different context when necessary. Hope that makes sense!

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

2 participants