0/24
23. Validated RPCs

Lesson 23: Validated RPCs

live.validated() automatically validates input before your function runs:

export const addUser = live.validated(
  { name: 'string', email: 'email', age: 'number' },
  (ctx, input) => {
    // input is guaranteed valid
  }
);

The schema maps field names to type validators. Built-in types:

  • 'string' - must be a string
  • 'number' - must be a number
  • 'boolean' - must be a boolean
  • 'email' - must be a string matching name@domain.tld

Before your function runs, live.validated checks every field. If any field is missing or fails its type check, it throws a LiveError with code 'VALIDATION'. Your function never executes with bad data.

In production, live.validated works with schema libraries like Zod or Valibot for full control. The built-in type strings shown here are a simplified version for this tutorial - in a real app you'd define custom validators like email format yourself.

Try it

  1. Replace live() with live.validated() on addContact
  2. Define the schema: { name: 'string', email: 'email', age: 'number' }
  3. Remove the manual validation checks - live.validated handles them

Try submitting with a missing field, a wrong type, or an invalid email - the error appears automatically.

WebSocket
0
No messages yet
/