Course contentsShow
← React
Lesson 1614 of 2,39639. Server Components in PracticeFree lesson

Returning Validation Errors

Sending validation errors back to the client and displaying them inline with form fields.

Returning Validation Errors

What you'll learn: How to send validation errors from server actions back to the client and display them alongside form fields.

The Problem with Server-Side Validation

You've learned how to validate input on the server in your server actions. But what happens when validation fails? The user needs to know what went wrong and where. Just throwing an error isn't enough—you need to send structured feedback back to the client.

Returning Error Objects

When validation fails, your server action can return an object containing the errors instead of performing the intended operation:

'use server'

async function createUser(formData: FormData) {
  const email = formData.get('email')
  const password = formData.get('password')
  
  // Validate
  const errors: Record<string, string> = {}
  if (!email || !email.includes('@')) {
    errors.email = 'Valid email is required'
  }
  if (!password || password.length < 8) {
    errors.password = 'Password must be at least 8 characters'
  }
  
  // Return errors if any exist
  if (Object.keys(errors).length > 0) {
    return { errors }
  }
  
  // Otherwise, proceed with creating user
  // ... database logic
  return { success: true }
}

Your client component can then read this return value and display errors inline with each field—exactly where the user needs to see them.

The Pattern

Think of it like a restaurant sending back your order ticket with red marks next to items that aren't available. You get specific feedback for each item, not just "something's wrong."

Key Takeaway: Server actions can return validation error objects that map field names to error messages, allowing you to display precise, inline feedback in your forms.