Blog>
Snippets

Validating Configurations with Custom Validators in TanStack Config

Create and apply custom validators to configuration properties using TanStack Config to ensure the integrity and correctness of application settings before application startup.
import { defineConfig, validate } from 'tanstack-config';

// Custom validator function for an email configuration
const emailValidator = (value) => {
  const emailRegex = /^\S+@\S+\.\S+$/;
  if (!emailRegex.test(value)) {
    throw new Error('Invalid email format');
  }
};

// Define the configuration with custom validators
const config = defineConfig({
  email: validate('user@example.com', emailValidator),
  // Additional configuration properties here
});
This code snippet demonstrates how to use TanStack Config's `defineConfig` and `validate` functions to define an application configuration that includes a custom validator. The `emailValidator` function checks if the provided email adheres to a basic format, throwing an error for invalid formats. This configuration ensures that the email setting is validated against the custom logic before the application fully starts, enhancing the integrity of the application settings.