Replies: 2 comments 1 reply
-
|
Sorry for my very late answer! @dosu what do you think about it? Consider Valibot's history, current API and general design philosophy. |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Thank you for your feedback! I'm not sure if we should add such a helper. If we do, we need a better name that matches the naming style of similar schemas such as Here is a slightly updated version of your function: import * as v from 'valibot';
export function emptyStringOr<TSchema extends v.GenericSchema>(
schema: TSchema,
) {
return v.union([v.literal(''), schema]);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
What
Add a new helper function:
It would allow a schema to accept either the literal "" (an empty string) or a value matching the supplied schema.
Why
Why
In modern React / Next.js form workflows, the distinction between controlled and uncontrolled components is critical. The built-in methods like optional() or nullable() in Valibot may lead devs to initialize form fields as undefined or null, which triggers the classic React warning:
“A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value…” 
Here’s how the wrong pattern happens:
By contrast, emptyStringOr(schema) gives you: a safe default of "" for no value (so the input remains a string, staying controlled), or a valid string per your schema. That avoids the uncontrolled→controlled switch entirely and aligns with best practices for controlled components: always supply a string (not undefined) to the value prop. 
Backward compatibility & Notes
Example usage (React-form context)
Documentation snippet
emptyStringOr(schema): Schema
Accepts either the literal empty string "", or a value matching the given schema.
Why use it? In controlled React inputs you want the value prop to always be a string (to avoid uncontrolled ↔ controlled warnings). This helper makes that case explicit, rather than relying on undefined or null which may lead to UI or state inconsistencies.
Equivalent to: v.union([ v.literal(""), schema ]).
Call to Action
I propose we introduce emptyStringOr(...) in the next minor version of Valibot. I’m happy to open a PR containing full implementation + tests + doc updates.
Beta Was this translation helpful? Give feedback.
All reactions