Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add validation support (Zod & others) #448

Draft
wants to merge 1 commit into
base: next
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion packages/nuqs/src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,27 @@ export type ParserBuilder<T> = Required<Parser<T>> &
*/
withOptions<This, Shallow>(this: This, options: Options<Shallow>): This

/**
* Pass in a validation function to perform runtime checks on the parsed
* value. If the validation fails, the value will be set to `null` (or
* the default value if specified).
*
* Validation must be synchronous, and must throw an error on invalid
* inputs.
*
* Example with Zod:
* ```ts
* const [posInt, setPosInt] = useQueryState(
* 'value',
* parseAsInteger.withValidation(z.number().positive().parse)
* )
* ```
*
* @param this
* @param validate
*/
withValidation<This>(this: This, validate: (input: unknown) => T): This

/**
* Specifying a default value makes the hook state non-nullable when the
* query is missing from the URL.
Expand Down Expand Up @@ -119,6 +140,18 @@ export function createParser<T>(
eq: (a, b) => a === b,
...parser,
parseServerSide: parseServerSideNullable,
withValidation(validate) {
return {
...this,
parse: (value: string) => {
const parsed = parser.parse(value)
if (parsed === null) {
return null
}
return validate(parsed)
}
}
},
withDefault(defaultValue) {
return {
...this,
Expand All @@ -128,7 +161,7 @@ export function createParser<T>(
}
}
},
withOptions(options: Options) {
withOptions(options) {
return {
...this,
...options
Expand Down