Skip to content

Optional string schema with regex #613

Answered by fabian-hiller
aokigit asked this question in Q&A
Discussion options

You must be logged in to vote

An empty form field will not return null or undefined. 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.

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.

Replies: 3 comments 6 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by aokigit
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
6 replies
@megacherry
Comment options

@megacherry
Comment options

@fabian-hiller
Comment options

@fabian-hiller
Comment options

@fabian-hiller
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants