Validators Overview
What are Validators?
Section titled “What are Validators?”Validators in Phaser Hooks are functions that validate state values before they are set. They help ensure data integrity and catch errors early in your game development.
How Validators Work
Section titled “How Validators Work”A validator function receives a value and returns:
- trueif the value is valid
- falseor a- stringerror message if the value is invalid
When a validator fails, Phaser Hooks will throw an error, so you must wrap validator usage in try/catch blocks.
Basic Usage
Section titled “Basic Usage”import { withLocalState, validators } from 'phaser-hooks';
export class GameScene extends Phaser.Scene {  create() {    // Create state with validator    const playerHealth = withLocalState(this, 'health', 100, {      validator: validators.numberRange(0, 100)    });
    // Always wrap state updates in try/catch when using validators    try {      playerHealth.set(50); // ✅ Valid - within range      playerHealth.set(150); // ❌ Throws error - outside range    } catch (error) {      console.error('Invalid health value:', error.message);    }  }}import { withLocalState, validators } from 'phaser-hooks';
export class GameScene extends Phaser.Scene {  create() {    // Create state with validator    const playerHealth = withLocalState(this, 'health', 100, {      validator: validators.numberRange(0, 100)    });
    // Always wrap state updates in try/catch when using validators    try {      playerHealth.set(50); // ✅ Valid - within range      playerHealth.set(150); // ❌ Throws error - outside range    } catch (error) {      console.error('Invalid health value:', error.message);    }  }}Built-in Validators
Section titled “Built-in Validators”Phaser Hooks provides several built-in validators:
- Number Range - Validates numbers within a range
- Non-Empty String - Validates non-empty strings
- Array Length - Validates array length
- One Of - Validates against allowed values
Error Handling Best Practices
Section titled “Error Handling Best Practices”Pattern 1: Try/Catch for Individual Updates
Section titled “Pattern 1: Try/Catch for Individual Updates”const playerState = withLocalState(this, 'player', { health: 100 }, {  validator: validators.numberRange(0, 100)});
function healPlayer(amount: number) {  try {    const currentHealth = playerState.get();    playerState.set(currentHealth + amount);  } catch (error) {    console.error('Healing failed:', error.message);    // Handle the error appropriately  }}const playerState = withLocalState(this, 'player', { health: 100 }, {  validator: validators.numberRange(0, 100)});
function healPlayer(amount) {  try {    const currentHealth = playerState.get();    playerState.set(currentHealth + amount);  } catch (error) {    console.error('Healing failed:', error.message);    // Handle the error appropriately  }}Pattern 2: Validation Helper Function
Section titled “Pattern 2: Validation Helper Function”function safeSetState<T>(state: HookState<T>, value: T, context: string) {  try {    state.set(value);    return true;  } catch (error) {    console.error(`${context} validation failed:`, error.message);    return false;  }}
// Usageconst success = safeSetState(playerHealth, 75, 'Player healing');if (!success) {  // Handle validation failure}function safeSetState(state, value, context) {  try {    state.set(value);    return true;  } catch (error) {    console.error(`${context} validation failed:`, error.message);    return false;  }}
// Usageconst success = safeSetState(playerHealth, 75, 'Player healing');if (!success) {  // Handle validation failure}When to Use Validators
Section titled “When to Use Validators”✅ Good Use Cases
Section titled “✅ Good Use Cases”- Player stats (health, mana, experience)
- Game configuration (difficulty levels, settings)
- Inventory items (ensuring valid item types)
- UI state (ensuring valid screen states)
❌ Avoid Validators For
Section titled “❌ Avoid Validators For”- Frequent updates (like position coordinates)
- Temporary values (like animation states)
- Performance-critical code (validators add overhead)
Next Steps
Section titled “Next Steps”- Number Range Validator - Learn about number validation
- Non-Empty String Validator - Learn about string validation
- Array Length Validator - Learn about array validation
- One Of Validator - Learn about enum validation
- Creating Custom Validators - Learn to create your own validators