Skip to content

Commit c372718

Browse files
committed
feat: merge schema defaults during cast for yup and valibot
1 parent 51b6865 commit c372718

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

packages/valibot/src/index.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
import { PartialDeep } from 'type-fest';
22
import type { TypedSchema, TypedSchemaError } from 'vee-validate';
3-
import { Output, Input, BaseSchema, BaseSchemaAsync, safeParseAsync, safeParse, Issue } from 'valibot';
4-
import { normalizeFormPath } from '../../shared';
3+
import {
4+
Output,
5+
Input,
6+
BaseSchema,
7+
BaseSchemaAsync,
8+
safeParseAsync,
9+
safeParse,
10+
Issue,
11+
getDefault,
12+
optional,
13+
} from 'valibot';
14+
import { isObject, merge, normalizeFormPath } from '../../shared';
515

616
export function toTypedSchema<
717
TSchema extends BaseSchema | BaseSchemaAsync,
@@ -32,8 +42,16 @@ export function toTypedSchema<
3242
}
3343

3444
const result = safeParse(valibotSchema, values);
45+
if (result.success) {
46+
return result.data;
47+
}
48+
49+
const defaults = getDefault(optional(valibotSchema));
50+
if (isObject(defaults) && isObject(values)) {
51+
return merge(defaults, values);
52+
}
3553

36-
return result.success ? result.data : values;
54+
return values;
3755
},
3856
};
3957

packages/yup/src/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { InferType, Schema, ValidateOptions, ValidationError } from 'yup';
22
import { TypedSchema, TypedSchemaError } from 'vee-validate';
33
import { PartialDeep } from 'type-fest';
4+
import { isObject, merge } from '../../shared';
45

56
export function toTypedSchema<TSchema extends Schema, TOutput = InferType<TSchema>, TInput = PartialDeep<TOutput>>(
67
yupSchema: TSchema,
@@ -51,6 +52,11 @@ export function toTypedSchema<TSchema extends Schema, TOutput = InferType<TSchem
5152
try {
5253
return yupSchema.cast(values);
5354
} catch {
55+
const defaults = yupSchema.getDefault();
56+
if (isObject(defaults) && isObject(values)) {
57+
return merge(defaults, values);
58+
}
59+
5460
return values;
5561
}
5662
},

0 commit comments

Comments
 (0)