Optional string schema with regex #613
-
I have a pretty basic schema like this and am using the new pipe function. export const UserSchema = object({
name: optional(pipe(string(), trim(), regex(/^[A-Za-z0-9\-_\. ]+$/, "Not optional after all"))),
}); I've tried all possible things, I'm also not quite sure if I like the new pipe functionality or if I just don't understand it correctly. Seems like an extra step to add to my schema and makes me want to go back to Zod 😢 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
An empty form field will not return import * as v from 'valibot';
const Schema = v.object({
name: v.union([
v.literal(''),
v.pipe(v.string(), v.trim(), v.regex(/^[\w\-. ]+$/iu)),
]),
}); We discussed the new API a few months ago in #463 and I talked about its benefits in #502. The feedback has been mostly positive, but I am aware that not everyone will like this change. Feel free to give me feedback. |
Beta Was this translation helpful? Give feedback.
-
I just looked at the documentation for I'll spend more time understanding and using the pipe function and will share feedback if I have any. |
Beta Was this translation helpful? Give feedback.
-
@fabian-hiller. Thanks for the answer. But this works not correctly or miss i something?
If i type for example only "j" the error output is "Invalid type: Expected "" | string but received "j"" and not: "Invalid length: Expected >=2 but received 1" |
Beta Was this translation helpful? Give feedback.
An empty form field will not return
null
orundefined
. Instead, it usually returns an empty string. Therefore, you need to look for a string that matches your regex or an empty string literal. Here is an example. You can execute and test it in our playground.We discussed the new API a few months ago in #463 and I talked about its benefits in #502. The feedback has been mostly positive, but I am aware that not everyone will like this change. Feel free to give me feedback.