Possible to validate extra requirements to optional field, in case a value is supplied? #503
Answered
by
fabian-hiller
ollebergkvist
asked this question in
Q&A
-
I'm working on a validation requirement where a postal code (postalcode) is considered optional if no value is supplied (an empty string). However, if a value is supplied, it must fulfill certain requirements. postalcode: optional( This fails for empty strings:
|
Beta Was this translation helpful? Give feedback.
Answered by
fabian-hiller
Apr 3, 2024
Replies: 1 comment 1 reply
-
Yes, this is possible but I would write it differently. Feel free to try it out in our playground. import * as v from 'valibot';
const Schema = v.union([
v.literal(''),
v.string([v.length(5, 'Postal code must be 5 digits'), v.decimal()]),
]); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ollebergkvist
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, this is possible but I would write it differently. Feel free to try it out in our playground.