fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.88k stars 181 forks source link

Conditionally validate #573

Closed kido1991 closed 3 months ago

kido1991 commented 3 months ago
import * as v from 'valibot';

const Schema = v.object({
  email: v.optional(v.string([v.email()])),
  password: v.string([v.minLength(1), v.minLength(8)]),
});

const result = v.safeParse(Schema, {
  email: '',
  password: '12345678',
});

console.log(result);

Hi,

From the example above, is it possible that if the email is empty do not validate with email() but only when it is not null or not empty string only then validate it?

Thanks

fabian-hiller commented 3 months ago

Yes it is. Here is an example:

import * as v from 'valibot';

const Schema = v.union([v.literal(''), v.string([v.email()])]);
kido1991 commented 3 months ago

Thanks! it's working now!