Bird
Raised Fist0
GraphQLquery~20 mins

Input validation patterns in GraphQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Input Validation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the result of this GraphQL query with input validation?

Given the following GraphQL schema snippet that validates an input argument age to be a positive integer, what will be the result of this query?

type Query {
  user(age: Int!): String
}

# Resolver logic:
# if age <= 0, return error "Invalid age"
# else return "User age is <age>"

Query:

{ user(age: -5) }
AError: age must be an integer
BUser age is -5
Cnull
DError: Invalid age
Attempts:
2 left
💡 Hint

Think about how the resolver handles invalid input values.

📝 Syntax
intermediate
2:00remaining
Which input validation directive syntax is correct in GraphQL?

Choose the correct syntax to validate that a string input email matches a simple email pattern using a custom directive @pattern.

Ainput UserInput { email: String! @pattern(regex: "^[^@\s]+@[^@\s]+\.[^@\s]+$") }
Binput UserInput { email: String! @pattern(value: "^[^@\s]+@[^@\s]+\.[^@\s]+$") }
Cinput UserInput { email: String! @validate(regex: "^[^@\s]+@[^@\s]+\.[^@\s]+$") }
Dinput UserInput { email: String! @pattern("^[^@\s]+@[^@\s]+\.[^@\s]+$") }
Attempts:
2 left
💡 Hint

Look for the correct argument name and syntax for directives.

🧠 Conceptual
advanced
2:00remaining
Why is input validation important in GraphQL APIs?

Which of the following is the best reason to implement input validation in GraphQL APIs?

ATo prevent invalid or malicious data from causing errors or security issues
BTo make queries run faster by skipping validation
CTo allow clients to send any data without restrictions
DTo reduce the size of the GraphQL schema
Attempts:
2 left
💡 Hint

Think about security and data integrity.

🔧 Debug
advanced
2:00remaining
Identify the error in this GraphQL input validation resolver

Consider this resolver function for a mutation that validates a username length:

async function createUser(parent, args) {
  if (args.username.length < 3) {
    throw new Error("Username too short");
  }
  // create user logic
  return { id: 1, username: args.username };
}

What error will occur if args.username is null?

ANo error, user created successfully
BError: Username too short
CTypeError: Cannot read property 'length' of null
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint

What happens when you try to access .length of null?

optimization
expert
3:00remaining
How to optimize input validation for nested GraphQL inputs?

You have a mutation that accepts a nested input object with multiple fields requiring validation. Which approach optimizes validation performance and maintainability?

AValidate all fields manually inside the resolver function with nested if statements
BUse reusable custom scalar types and directives for validation on each field
CSkip validation and trust client inputs to reduce server load
DValidate only the top-level input object and ignore nested fields
Attempts:
2 left
💡 Hint

Think about reusability and separation of concerns.

Practice

(1/5)
1. What is the main purpose of input validation in GraphQL schemas?
easy
A. To ensure data is safe and correct before processing
B. To speed up query execution
C. To automatically generate UI forms
D. To store data in multiple databases

Solution

  1. Step 1: Understand input validation role

    Input validation checks data before it is saved or used to avoid errors or security issues.
  2. Step 2: Identify main goal in GraphQL

    GraphQL uses input validation to keep data safe and correct before processing.
  3. Final Answer:

    To ensure data is safe and correct before processing -> Option A
  4. Quick Check:

    Input validation = data safety and correctness [OK]
Hint: Input validation means checking data before use [OK]
Common Mistakes:
  • Confusing validation with performance optimization
  • Thinking validation auto-generates UI
  • Assuming validation stores data
2. Which of the following is a valid way to enforce input validation in a GraphQL schema?
easy
A. Using HTML tags in schema definitions
B. Writing SQL queries inside the schema
C. Adding CSS styles to input fields
D. Using custom scalar types for specific formats

Solution

  1. Step 1: Review GraphQL schema capabilities

    GraphQL schemas can define custom scalar types to validate formats like email or date.
  2. Step 2: Eliminate invalid options

    SQL queries, CSS, and HTML are unrelated to schema validation.
  3. Final Answer:

    Using custom scalar types for specific formats -> Option D
  4. Quick Check:

    Custom scalars = validation in schema [OK]
Hint: Custom scalars validate input formats in GraphQL [OK]
Common Mistakes:
  • Confusing schema with UI styling
  • Trying to embed SQL in schema
  • Using HTML tags in schema definitions
3. Given this GraphQL input type and resolver snippet, what happens if the input 'username' is an empty string?
input UserInput {
  username: String!
}

resolver createUser(input: UserInput) {
  if (input.username.length === 0) {
    throw new Error('Username cannot be empty');
  }
  return saveUser(input);
}
medium
A. The resolver ignores the username field
B. The resolver throws an error and user is not saved
C. The user is saved with an empty username
D. The schema rejects the query before resolver runs

Solution

  1. Step 1: Analyze resolver input check

    The resolver checks if username length is zero and throws an error if true.
  2. Step 2: Understand effect of empty string input

    Empty string triggers the error, so user is not saved.
  3. Final Answer:

    The resolver throws an error and user is not saved -> Option B
  4. Quick Check:

    Empty username triggers error in resolver [OK]
Hint: Empty string triggers error in resolver check [OK]
Common Mistakes:
  • Assuming schema rejects empty string automatically
  • Thinking empty username is saved
  • Ignoring resolver error handling
4. Identify the error in this GraphQL input validation snippet:
input ProductInput {
  price: Float!
}

resolver addProduct(input: ProductInput) {
  if (input.price < 0) {
    return 'Price must be positive';
  }
  saveProduct(input);
  return 'Product added';
}
medium
A. Returning a string error instead of throwing an error
B. Missing input type declaration
C. Using Float instead of Int for price
D. No validation for price being zero

Solution

  1. Step 1: Check error handling in resolver

    The resolver returns a string on error instead of throwing an error, which may not stop execution properly.
  2. Step 2: Understand proper error signaling

    Throwing an error is standard to halt processing and signal failure in GraphQL.
  3. Final Answer:

    Returning a string error instead of throwing an error -> Option A
  4. Quick Check:

    Errors should be thrown, not returned as strings [OK]
Hint: Throw errors, don't return error strings in resolvers [OK]
Common Mistakes:
  • Returning error messages instead of throwing
  • Confusing Float and Int types
  • Ignoring zero price validation
5. You want to enforce that a user's email input is always lowercase and matches a valid email format in GraphQL. Which combination is the best approach?
hard
A. Use a directive to reject any uppercase letters without transformation
B. Only rely on GraphQL's String type without extra checks
C. Use a custom scalar for email format and transform input to lowercase in resolver
D. Validate email format in the database after saving

Solution

  1. Step 1: Understand validation needs

    Email must be valid format and lowercase before saving or processing.
  2. Step 2: Choose best GraphQL validation method

    Custom scalar can enforce format; resolver can transform input to lowercase.
  3. Step 3: Evaluate other options

    Relying only on String misses validation; directives alone can't transform; database validation is late.
  4. Final Answer:

    Use a custom scalar for email format and transform input to lowercase in resolver -> Option C
  5. Quick Check:

    Custom scalar + resolver transform = best validation [OK]
Hint: Combine custom scalar and resolver for format and case [OK]
Common Mistakes:
  • Skipping format validation
  • Expecting directives to transform input
  • Validating only after saving data