Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
zod-form-data
Advanced tools
Validation helpers for [zod](https://github.com/colinhacks/zod) specifically for parsing `FormData` or `URLSearchParams`. This is particularly useful when using [Remix](https://github.com/remix-run/remix) and combos well with [remix-validated-form](https:
Validation helpers for zod
specifically for parsing FormData
or URLSearchParams
.
This is particularly useful when using Remix
and combos well with remix-validated-form.
The main goal of this library is deal with the pain point that everything in FormData
is a string.
Sometimes, properly validating this kind of data requires a lot of extra hoop jumping and preprocessing.
With the helpers in zod-form-data
, you can write your types closer to how you want to.
import { zfd } from "zod-form-data";
const schema = zfd.formData({
name: zfd.text(),
age: zfd.numeric(z.number().min(25).max(50)),
likesPizza: zfd.checkbox(),
});
// This example is using Remix, but it will work
// with any `FormData` or `URLSearchParams` no matter where you get it from.
export const action = async ({ request }) => {
const { name, age, likesPizza } = schema.parse(await request.formData());
// do something with parsed data
};
npm install zod-form-data
The eventual goal is to have a helper to preprocess and/or validate most types of native inputs. If you have a helper for an input type that isn't in this library, feel free to open a PR to add it!
Contents
This helper takes the place of the z.object
at the root of your schema.
It wraps your schema in a z.preprocess
that extracts all the data out of a FormData
and transforms it into a regular object.
If the FormData
contains multiple entries with the same field name,
it will automatically turn that field into an array.
(If you're expecting multiple values for a field, use repeatable.)
The primary use-case for this helper is to accept FormData
,
but it works with any iterable that returns entries.
This means it can accept URLSearchParams
or regular objects as well.
You can use this the same way you would use z.object
.
const schema = zfd.formData({
field1: zfd.text(),
field2: zfd.text(),
});
const someFormData = new FormData();
const dataObject = schema.parse(someFormData);
It's also possible to pass a zod schema to formData
.
const schema = zfd.formData(
z.object({
field1: zfd.text(),
field2: zfd.text(),
})
);
Transforms any empty strings to undefined
before validating.
This makes it so empty strings will fail required checks,
allowing you to use optional
for optional fields instead of nonempty
for required fields.
If you call zfd.text
with no arguments, it will assume the field is a required string by default.
If you want to customize the schema, you can pass that as an argument.
const const schema = zfd.formData({
requiredString: zfd.text(),
stringWithMinLength: zfd.text(z.string().min(10)),
optional: zfd.text(z.string().optional()),
})
Coerces numerical strings to numbers transforms empty strings to undefined
before validating.
If you call zfd.number
with no arguments,
it will assume the field is a required number by default.
If you want to customize the schema, you can pass that as an argument.
Note: The preprocessing only coerces the value into a number. It doesn't use parseInt
.
Something like "24px"
will not be transformed and will be treated as a string.
const schema = zfd.formData({
requiredNumber: zfd.numeric(),
numberWithMin: zfd.numeric(z.number().min(13)),
optional: zfd.numeric(z.number().optional()),
});
Validates a checkbox field as a boolean.
Unlike other helpers, this is not a preprocesser,
but a complete schema that should do everything you need.
By default, it will treat "on"
as true and undefined
as false,
but you can customize the true value.
If you have a checkbox group and you want to leave the values as strings, repeatableField might be what you want.
const schema = zfd.formData({
defaultCheckbox: zfd.checkbox(),
checkboxWithValue: zfd.checkbox({ trueValue: "true" }),
mustBeTrue: zfd.checkbox().refine((val) => val, "Please check this box"),
});
If you're used to using client-side form libraries and haven't dealt with native form behavior much, the native checkbox behavior might be non-intuitive (it was for me).
Take this checkbox:
<input name="myCheckbox" type="checkbox" />
If you check this checkbox and submit the form, the value in the FormData
will be "on"
.
If you add a value prop:
<input name="myCheckbox" type="checkbox" value="someValue" />
Then the checked value of the checkbox will be "someValue"
instead of "on"
.
If you leave the checkbox unchecked,
the FormData
will not include an entry for myCheckbox
at all.
Transforms any empty File objects to undefined
before validating.
This makes it so empty files will fail required checks,
allowing you to use optional
for optional fields.
If you call zfd.file
with no arguments, it will assume the field is a required file by default.
const schema = zfd.formData({
requiredFile: zfd.file(),
optional: zfd.file(z.instanceof(File).optional()),
});
There is a unique case in Remix when using a CustomUploadHandler,
the field will be a File
on the client side, but an ID string (or URL) after uploading on the server.
In this case you will need the schema to switch to string on the server:
const baseSchema = z.object({
someOtherField: zfd.text(),
});
const clientSchema = z.formData(
baseSchema.and({
file: zfd.file(),
})
);
const serverSchema = z.formData(
baseSchema.and({
file: z.string(),
})
);
Note: This will return File | string
for the type. TODO: Example of type safety for this
Preprocesses a field where you expect multiple values could be present for the same field name
and transforms the value of that field to always be an array.
This is specifically meant to work with data transformed by zfd.formData
(or by remix-validated-form
).
If you don't provide a schema, it will assume the field is an array of zfd.text fields. If you want to customize the type of the item, but don't care about validations on the array itself, you can use repeatableOfType.
const schema = zfd.formData({
myCheckboxGroup: zfd.repeatable(),
atLeastOneItem: zfd.repeatable(z.array(zfd.text()).min(1)),
});
A convenience wrapper for repeatable. Instead of passing the schema for an entire array, you pass in the schema for the item type.
const schema = zfd.formData({
repeatableNumberField: zfd.repeatableOfType(zfd.numeric()),
});
FAQs
Validation helpers for [zod](https://github.com/colinhacks/zod) specifically for parsing `FormData` or `URLSearchParams`. This is particularly useful when using [Remix](https://github.com/remix-run/remix) and combos well with [remix-validated-form](https:
The npm package zod-form-data receives a total of 40,079 weekly downloads. As such, zod-form-data popularity was classified as popular.
We found that zod-form-data demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.