Blog>
Snippets

Defining Schema Validation for Search Params in TanStack Router

Showcase a code example where a specific schema is defined for search parameters using TanStack Router, ensuring each parameter meets the defined data type and structure.
import { z } from 'zod';
Import Zod for schema creation and validation.
const searchParamSchema = z.object({
  searchTerm: z.string(),
  pageSize: z.number().min(1),
  pageIndex: z.number().nonnegative()
});
Define a schema for the search parameters using Zod, specifying the expected type and constraints for each parameter.
function validateSearchParams(params) {
  try {
    searchParamSchema.parse(params);
    return true; // Validation successful
  } catch (error) {
    console.error('Validation error:', error);
    return false; // Validation failed
  }
}
Function to validate the search parameters against the defined schema. Returns true if validation is successful, otherwise logs the error and returns false.
const searchParams = { searchTerm: 'example', pageSize: 10, pageIndex: 0 };
const isValid = validateSearchParams(searchParams);
Example usage of the validateSearchParams function, passing in some search parameters to validate against the schema.