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

Feature request: optional should have a default value #48

Open
gdamjan opened this issue May 28, 2019 · 2 comments
Open

Feature request: optional should have a default value #48

gdamjan opened this issue May 28, 2019 · 2 comments

Comments

@gdamjan
Copy link

gdamjan commented May 28, 2019

something like:

toi
  .optional({default:20})
  .and(toi.num.is())

or just:

toi
  .optional(20)
  .and(toi.num.is())
@hf
Copy link
Owner

hf commented Jun 3, 2019

The thing about "defaults" is that they're much more useful if appended at the end (or in the middle of) a validation chain.

The validator contract is: if receiving null or undefined at input, you must return null or undefined respectively at output. toi.required is the only one allowed to break the contract, to disallow nulls or undefined.

So generally toi.required starts the chain if you really don't want any nulls. toi.optional does almost nothing, except that it strictly types the start as having something | null.

The default then should maybe come at the end of a chain (or proper place):

toi.optional() // possible null values
  .and(toi.str.is()) // but must be a string if present
  .and(toi.default("STRING")) // if null or undefined

@hf
Copy link
Owner

hf commented Jun 3, 2019

Nevermind, I see your point. It can go at the top! I'll implement it soon.

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