Created
March 22, 2023 09:01
-
-
Save chenasraf/3532e1b13a63241cc1d4e78581981e15 to your computer and use it in GitHub Desktop.
Zod - Validate Specific Field from Schema (good for forms)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type R = Record<string | number, any> | |
export function parseFieldSafe<T extends Zod.AnyZodObject, K extends keyof Zod.infer<T>>( | |
obj: T, | |
key: K, | |
value: T[K], | |
): Zod.SafeParseReturnType<R, R> { | |
return obj.pick({ [key]: true as const }).safeParse({ [key]: value }) | |
} | |
export function isFieldValid<T extends Zod.AnyZodObject, K extends keyof Zod.infer<T>>( | |
obj: T, | |
key: K, | |
value: T[K], | |
): boolean { | |
return parseFieldSafe(obj, key, value).success | |
} | |
export function parseField<T extends Zod.AnyZodObject, K extends keyof Zod.infer<T>>( | |
obj: T, | |
key: K, | |
value: T[K], | |
): T { | |
return obj.pick({ [key]: true as const }).parse({ [key]: value }) as T | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment