How to Use Directive for Validation in GraphQL
In GraphQL, you can use
directives to add validation rules by defining custom directives in your schema and implementing their logic in your server code. These directives act like annotations on fields or arguments to enforce rules such as length, format, or required values during query execution.Syntax
A validation directive in GraphQL is defined using the directive keyword in the schema. It specifies where the directive can be applied (e.g., FIELD_DEFINITION, ARGUMENT_DEFINITION) and any arguments it accepts.
Example parts:
@directiveName: The name of the directive.on FIELD_DEFINITION | ARGUMENT_DEFINITION: Locations where the directive can be used.- Arguments inside parentheses define parameters for validation.
graphql
directive @length(min: Int, max: Int) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
Example
This example shows a @length directive that validates the length of a string argument. The directive is declared in the schema and then used on an argument. The server code checks the directive and enforces the validation.
graphql
schema {
query: Query
}
directive @length(min: Int, max: Int) on ARGUMENT_DEFINITION
type Query {
greet(name: String @length(min: 3, max: 10)): String
}
// Server-side pseudo code example (Node.js with Apollo Server):
// const { SchemaDirectiveVisitor, defaultFieldResolver } = require('apollo-server');
// class LengthDirective extends SchemaDirectiveVisitor {
// visitArgumentDefinition(arg) {
// const { min, max } = this.args;
// const { resolve = defaultFieldResolver } = arg;
// arg.resolve = async function (source, args, context, info) {
// const value = args[arg.name];
// if (value.length < min || value.length > max) {
// throw new Error(`Argument '${arg.name}' length must be between ${min} and ${max}`);
// }
// return resolve(source, args, context, info);
// };
// }
// }Output
Query greet with name shorter than 3 or longer than 10 characters returns error: "Argument 'name' length must be between 3 and 10"
Common Pitfalls
Common mistakes when using validation directives include:
- Not implementing the directive logic on the server, so the directive has no effect.
- Applying directives to unsupported schema locations.
- Ignoring validation errors and returning incorrect data.
- Using directives only in schema without connecting them to resolver logic.
graphql
directive @length(min: Int, max: Int) on FIELD_DEFINITION # Wrong: Applying @length on FIELD_DEFINITION instead of ARGUMENT_DEFINITION type Query { greet(name: String @length(min: 3, max: 10)): String } # Right: Directive declared on ARGUMENT_DEFINITION and used on argument directive @length(min: Int, max: Int) on ARGUMENT_DEFINITION type Query { greet(name: String @length(min: 3, max: 10)): String }
Quick Reference
Tips for using validation directives in GraphQL:
- Define directives with clear argument names for validation rules.
- Apply directives to arguments or input fields where validation is needed.
- Implement directive logic in your server to enforce validation.
- Throw errors in directive logic to stop invalid queries.
- Test directives thoroughly to ensure they work as expected.
Key Takeaways
Define custom validation directives in your GraphQL schema using the directive keyword.
Apply directives to arguments or input fields to specify validation rules.
Implement directive logic on the server to enforce validation during query execution.
Always throw errors in directive logic to prevent invalid data from passing.
Test your directives to avoid common mistakes like unsupported locations or missing logic.