0
0
GraphQLquery~5 mins

Input validation patterns in GraphQL

Choose your learning style9 modes available
Introduction

Input validation helps make sure the data sent to a GraphQL server is correct and safe. It stops errors and bad data from causing problems.

When users submit forms with data like names, emails, or passwords.
When APIs receive data from other systems and need to check it before saving.
When you want to prevent invalid or harmful data from entering your database.
When you want to give clear error messages if the input is wrong.
When you want to enforce rules like minimum length or allowed characters.
Syntax
GraphQL
type Mutation {
  createUser(input: CreateUserInput!): User
}

input CreateUserInput {
  username: String!
  email: String!
  age: Int
}

# Validation happens in resolver or with custom scalars/directives

GraphQL schema defines the shape of input but does not do all validation automatically.

Use custom scalars or directives for advanced validation like patterns or ranges.

Examples
Defines required username and email, optional age.
GraphQL
input CreateUserInput {
  username: String!
  email: String!
  age: Int
}
Custom scalar Email can validate email format automatically.
GraphQL
scalar Email

input CreateUserInput {
  username: String!
  email: Email!
}
Directive enforces username length between 3 and 15 characters.
GraphQL
directive @length(min: Int, max: Int) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

input CreateUserInput {
  username: String! @length(min: 3, max: 15)
}
Sample Program

This mutation creates a user after checking the input meets simple rules like username length and email format.

GraphQL
type Mutation {
  createUser(input: CreateUserInput!): User
}

input CreateUserInput {
  username: String!
  email: String!
  age: Int
}

type User {
  id: ID!
  username: String!
  email: String!
  age: Int
}

# Resolver example (pseudocode):
# if input.username.length < 3 then throw error
# if input.email does not match email pattern then throw error
# else create user and return

# Mutation example:
mutation {
  createUser(input: {username: "Sam", email: "sam@example.com", age: 25}) {
    id
    username
    email
    age
  }
}
OutputSuccess
Important Notes

GraphQL schema types ensure basic type safety but do not replace full validation.

Use custom scalars or validation libraries in resolvers for better input checks.

Clear error messages help users fix their input mistakes quickly.

Summary

Input validation keeps data safe and correct before saving or processing.

GraphQL schema defines input shapes but advanced checks need custom code or scalars.

Use directives, custom scalars, or resolver logic to enforce rules like length or format.