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.
Input validation patterns in GraphQL
type Mutation {
createUser(input: CreateUserInput!): User
}
input CreateUserInput {
username: String!
email: String!
age: Int
}
# Validation happens in resolver or with custom scalars/directivesGraphQL 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.
input CreateUserInput {
username: String!
email: String!
age: Int
}scalar Email
input CreateUserInput {
username: String!
email: Email!
}directive @length(min: Int, max: Int) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
input CreateUserInput {
username: String! @length(min: 3, max: 15)
}This mutation creates a user after checking the input meets simple rules like username length and email format.
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
}
}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.
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.