Is there a way to sanitise request inputs using zod? #1358
-
Hey everyone, I'm new to zod. I'm wondering If is it possible to sanitize parsed requests using the For example: let's say I have a I'm open to using any other packages to sanitize inputs, if it works well with zod. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 6 replies
-
You can use the const s = z.object({ email: z.string(), pass: z.string() }).transform(v => {
return {
email: sanitize(v.email),
pass: sanitize(v.pass),
}
}) |
Beta Was this translation helpful? Give feedback.
-
so one needs an external/other function/library to sanitize, |
Beta Was this translation helpful? Give feedback.
-
Try this import { z } from "zod";
const escapeHtml = (text: string) => {
const map: Record<string, string> = {
"<": "<",
">": ">",
"&": "&",
"'": "'",
'"': """,
"/": "/",
};
return text.replace(/[<>&'"\/]/g, (char: string): string => map[char]);
};
const safeHtmlString = z.string().transform((str) => escapeHtml(str));
// Example Usage
try {
const safeText = safeHtmlString.parse('<script>alert("hi")</script>');
console.log(safeText); // <script>alert("hi")</script>
} catch (error) {
console.error(error);
} |
Beta Was this translation helpful? Give feedback.
-
I wanted to share what I use in our codebase. import {type z} from 'zod';
/**
* Enhances a Zod schema by providing a default value for inputs that may be null or undefined.
*
* Unlike the `.default()` method, which only applies when a key is missing, this function
* ensures that nullish values (null or undefined) are also handled appropriately, providing
* a consistent output by transforming them into the given default value.
*
* @example
* const ModelSchema = z.object({
* title: z.string(),
* userName: addDefaultValue(z.string(), 'Anonymous'),
* tags: addDefaultValue(z.array(z.string()), []),
* optionalComment: addDefaultValue(z.string(), ''),
* });
*/
export function addDefaultValue<T>(schema: z.ZodType<T>, defaultValue: T) {
return schema.nullish().transform((value) => value ?? defaultValue) as z.ZodType<T>;
/* // todo: should we validate the defaultValue data?
return schema
.nullish()
.transform((value) => value ?? defaultValue)
.pipe(schema) as z.ZodType<T>;
*/
} |
Beta Was this translation helpful? Give feedback.
You can use the
.transform()
method with any sanitization function on the schema: