Comments (11)
Thanks for creating this issue! No, Valibot does not provide an option to automatically coerce or transform string values into other data types. With Valibot you have to use coerce
to transform a value before validation or transform
to do the same afterwards.
from valibot.
const UserSchema = object({
age: coercedNumber([toMinValue(8)]),
isEmployed: coercedBoolean(),
groups: coercedArray<string>(minLength(3))
});
ajv has defined coercion rules pretty clearly, these should cover all the common cases: https://ajv.js.org/coercion.html
Handling strings, numbers, booleans and arrays is going to cover 90% of use-cases. There are some extra cases like Dates, but these are much less important.
from valibot.
We've implemented a bunch of coercion rules in TS back in the day when zod didn't have any, feel free to reuse any of the code if it helps:
https://github.com/lokalise/zod-extras/tree/main/src/utils
from valibot.
@fabian-hiller coerce
works fine but I agree with you, it's insecure because it accept all possible value. I create functions toBoolean
, toNumber
to convert correctly only if source is string. Otherwise, I return the passed value to avoid unwanted conversion of type : For example, Number(null)
return 0
and Number(undefined)
return NaN
and we don't want that, if we have null
or undefined
, we want to return it
from valibot.
@fabian-hiller Would you consider adding such functionality, though? Not having it severely limits usefullness of valibot for validating REST API requests.
from valibot.
How would you design the API for this? Feel free to share sample code (how you want to write the schema) with me. Keep in mind that this library follows a modular design.
from valibot.
all coercedX types first attempt the coercion based on the hardcoded rules, then validate the coercion result, then apply any more granular rules defined.
from valibot.
This is already possible with coerce
. Do you prefer your solution for DX reasons? Read more here: https://valibot.dev/guides/methods/#coerce
const UserSchema = object({
age: v.coerce(v.number([toMinValue(8)]), Number),
isEmployed: v.coerce(v.boolean(), Boolean),
// ...
});
Note: I plan to remove coerce
when merging #502. The reason for this is that coerce
is insecure because the input can be anything. This can lead to bugs and security risks, especially when used by less experienced developers. The new API to accomplish the same goal will look like this:
const UserSchema = v.object({
age: v.pipe(v.unknown(), v.transform(Number), v.toMinValue(8)),
isEmployed: v.pipe(v.unknown(), v.transform(Boolean)),
// ...
});
This approach requires that the input type be explicitly defined. If you know you will always expect a string, you should change the scheme to the following
const UserSchema = v.object({
age: v.pipe(v.string(), v.transform(Number), v.toMinValue(8)),
isEmployed: v.pipe(v.string(), v.transform(Boolean)),
// ...
});
from valibot.
@fabian-hiller This is neat, thanks!
One use-case which this doesn't seem to cover is array coercing. When you are dealing with request query params, and you receive an array of strings consisting of a single element, frameworks will parse that as just a string. In that case you can't define a string schema, your input might be a string (which you want to convert to an array with one element) or an array with 2+ elements (in which case you just accept it as-is.
Would it be possible to either skip first validation step or have a check for XorArrayOfX? And to have a transform for arrays which does nothing if already correct type?
from valibot.
Would groups: v.pipe(v.unknown(), v.transform(Array))
work correctly for both arrays and strings?
from valibot.
One use-case which this doesn't seem to cover is array coercing...
Wouldgroups: v.pipe(v.unknown(), v.transform(Array))
work correctly for both arrays and strings?
Can you send me the possible inputs with the output you expect. I am pretty sure there is a simple solution for this.
from valibot.
Related Issues (20)
- Conditionally validate HOT 2
- Not correct lang after set globally lang HOT 3
- `forward` not working when `transform` field throwing error HOT 3
- [i18n] add Polish(pl) language
- Record with params (key, value, pipe) return error TS2769 HOT 4
- Invalid type error while trying to parse process.env object HOT 4
- Unable to use `lazy()` in `variant()` HOT 1
- New fields in existing schema HOT 6
- Type instantiation is excessively deep and possively Infinite HOT 4
- [i18n] Add Spanish language HOT 1
- Empty array in optional as a default value turns the type into union of the type or never HOT 6
- Build error HOT 4
- Add `items` action HOT 1
- Can't run test code using 0.31.0-rc HOT 6
- Add an advanced `refine` method (similar to Zod's `superRefine`)
- [0.31.0-rc] Enable to perform transform on the first argument of pipe method HOT 2
- EMOJI_REGEX throws Invalid regular expression flags on node v18 HOT 4
- TypeScript: InferInput always infers intersect as 'never' HOT 3
- [v0.31.0-rc.5] `Invalid type: Expected Object but received Object` because of `edge` runtime HOT 1
- abortPipeEarly influnces on abortEarly HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from valibot.