GiraphQL
Search…
Validation
A plugin for adding validation for field arguments based on zod. This plugin does not expose zod directly, but most of the options map closely to the validations available in zod.

Usage

Install

To use the validation plugin you will need to install both zod package and the validation plugin:
1
yarn add zod @giraphql/plugin-validation
Copied!

Setup

1
import ValidationPlugin from '@giraphql/plugin-validation';
2
const builder = new SchemaBuilder({
3
plugins: [ValidationPlugin],
4
});
5
6
builder.queryType({
7
fields: (t) => ({
8
simple: t.boolean({
9
nullable: true,
10
args: {
11
// Validate individual args
12
email: t.arg.string({
13
validate: {
14
email: true,
15
},
16
}),
17
phone: t.arg.string(),
18
},
19
// Validate all args together
20
validate: (args) => !!args.phone || !!args.email,
21
resolve: () => true,
22
}),
23
}),
24
});
Copied!

Examples

With custom message

1
builder.queryType({
2
fields: (t) => ({
3
withMessage: t.boolean({
4
nullable: true,
5
args: {
6
email: t.arg.string({
7
validate: {
8
email: [true, { message: 'invalid email address' }],
9
},
10
}),
11
phone: t.arg.string(),
12
},
13
validate: [
14
(args) => !!args.phone || !!args.email,
15
{ message: 'Must provide either phone number or email address' },
16
],
17
resolve: () => true,
18
}),
19
});
Copied!

Validating List

1
builder.queryType({
2
fields: (t) => ({
3
list: t.boolean({
4
nullable: true,
5
args: {
6
list: t.arg.stringList({
7
validate: {
8
items: {
9
email: true,
10
},
11
maxLength: 3,
12
},
13
}),
14
},
15
resolve: () => true,
16
}),
17
}),
18
});
Copied!

Using your own zod schemas

If you just want to use a zod schema defined somewhere else, rather than using the validation options you can use the schema option:
1
builder.queryType({
2
fields: (t) => ({
3
list: t.boolean({
4
nullable: true,
5
args: {
6
max5: t.arg.int({
7
validate: {
8
schema: zod.number().int().max(5),
9
},
10
}),
11
},
12
resolve: () => true,
13
}),
14
}),
15
});
Copied!

API

On Object fields

  • validate: Refinement<T> | Refinement<T>[].

On InputObjects

  • validate: Refinement<T> | Refinement<T>[]

On arguments and fields on InputObjects

  • validate: Refinement | ValidationOptions

Refinement

A Refinement is a function that will be passed to the zod refine method. It receives the args object, input object, or value of the specific field the refinement is defined on. It should return a boolean or Promise<boolean>.
Refinements can either be just a function: (val) => isValid(val), or an array with the function, and an options object like: [(val) => isValid(val), { message: 'field should be valid' }].
The options object may have a message property, and if the type being validated is an object, it can also include a path property with an array of strings indicating the path of the field in the object being validated. See the zod docs on refine for more details.

ValidationOptions

The validation options available depend on the type being validated. Each property of ValidationOptions can either be a value specific to the constraint, or an array with the value, and the options passed to the underlying zod method. This options object can be used to set a custom error message:
1
{
2
validate: {
3
max: [10, { message: 'should not be more than 10' }],
4
int: true,
5
}
6
}
Copied!

Number

  • type?: 'number'
  • refine?: Refinement<number> | Refinement<number>[]
  • min?: Constraint<number>
  • max?: Constraint<number>
  • positive?: Constraint<boolean>
  • nonnegative?: Constraint<boolean>
  • negative?: Constraint<boolean>
  • nonpositive?: Constraint<boolean>
  • int?: Constraint<boolean>
  • schema?: ZodSchema<number>

BigInt

  • type?: 'bigint'
  • refine?: Refinement<bigint> | Refinement<bigint>[]
  • schema?: ZodSchema<bigint>

Boolean

  • type?: 'boolean'
  • refine?: Refinement<boolean> | Refinement<boolean>[]
  • schema?: ZodSchema<boolean>

Date

  • type?: 'boolean'
  • refine?: Refinement<boolean> | Refinement<boolean>[]
  • schema?: ZodSchema<Date>

String

  • type?: 'string';
  • refine?: Refinement<string> | Refinement<string>[]
  • minLength?: Constraint<number>
  • maxLength?: Constraint<number>
  • length?: Constraint<number>
  • url?: Constraint<boolean>
  • uuid?: Constraint<boolean>
  • email?: Constraint<boolean>
  • regex?: Constraint<RegExp>
  • schema?: ZodSchema<string>

Object

  • type?: 'object';
  • refine?: Refinement<T> | Refinement<T>[]
  • schema?: ZodSchema<Ts>

Array

  • type?: 'array';
  • refine?: Refinement<T[]> | Refinement<T[]>[]
  • minLength?: Constraint<number>
  • maxLength?: Constraint<number>
  • length?: Constraint<number>
  • items?: ValidationOptions<T> | Refinement<T>
  • schema?: ZodSchema<T[]>

How it works

Each arg on an object field, and each field on an input type with validation will build its own zod validator. These validators will be a union of all potential types that can apply the validations defined for that field. For example, if you define an optional field with a maxLength validator, it will create a zod schema that looks something like:
1
zod.union([zod.null(), zod.undefined(), zod.array().maxLength(5), zod.string().maxLength(5)]);
Copied!
If you set and email validation instead the schema might look like:
1
zod.union([zod.null(), zod.undefined(), zod.string().email()]);
Copied!
At runtime, we don't know anything about the types being used by your schema, we can't infer the expected js type from the type definition, so the best we can do is limit the valid types based on what validations they support. The type validation allows explicitly validating the type of a field to be one of the base types supported by zod:
1
// field
2
{
3
validate: {
4
type: 'string',
5
maxLength: 5
6
}
7
// generated
8
zod.union([zod.null(), zod.undefined(), zod.string().maxLength(5)]);
Copied!
There are a few exceptions the above:
1: args and input fields that are InputObjects always use zod.object() rather than creating a union of potential types.
  1. 1.
    args and input fields that are list types always use zod.array().
  2. 2.
    If you only include a refine validation (or just pass a function directly to validate) we will just use zods unknown validator instead:
1
// field
2
{
3
validate: (val) => isValid(val),
4
}
5
// generated
6
zod.union([zod.null(), zod.undefined(), zod.unknown().refine((val) => isValid(val))]);
Copied!
If the validation options include a schema that schema will be used as an intersection wit the generated validator:
1
// field
2
{
3
validate: {
4
int: true,
5
schema: zod.number().max(10),
6
}
7
// generated
8
zod.union([zod.null(), zod.undefined(), zod.intersection(zod.number().max(10), zod.number().int())]);
Copied!

Sharing schemas with client code

The easiest way to share validators is the use the to define schemas for your fields in an external file using the normal zod APIs, and then attaching those to your fields using the schema option.
1
// shared
2
import { ValidationOptions } from '@giraphql/plugin-validation';
3
4
const numberValidation = zod.number().max(5);
5
6
// server
7
builder.queryType({
8
fields: (t) => ({
9
example: t.boolean({
10
args: {
11
num: t.arg.int({
12
validate: {
13
schema: numberValidation,
14
}
15
}),
16
},
17
resolve: () => true,
18
}),
19
});
20
});
21
22
// client
23
numberValidator.parse(3) // pass
24
numberValidator.parse('3') // fail
Copied!
You can also use the createZodSchema helper from the plugin directly to create zod Schemas from an options object:
1
// shared
2
import { ValidationOptions } from '@giraphql/plugin-validation';
3
4
const numberValidation: ValidationOptions<number> = {
5
max: 5,
6
};
7
8
// server
9
builder.queryType({
10
fields: (t) => ({
11
example: t.boolean({
12
args: {
13
num: t.arg.int({
14
validate: numberValidation,
15
}),
16
},
17
resolve: () => true,
18
}),
19
});
20
});
21
22
// client
23
import { createZodSchema } from '@giraphql/plugin-validation';
24
25
const validator = createZodSchema(numberValidator);
26
27
validator.parse(3) // pass
28
validator.parse('3') // fail
Copied!
Last modified 4d ago