Skip to content

Validators Overview

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.

A validator function receives a value and returns:

  • true if the value is valid
  • false or a string error 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.

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);
}
}
}

Phaser Hooks provides several built-in validators:

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
}
}
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;
}
}
// Usage
const success = safeSetState(playerHealth, 75, 'Player healing');
if (!success) {
// Handle validation failure
}
  • Player stats (health, mana, experience)
  • Game configuration (difficulty levels, settings)
  • Inventory items (ensuring valid item types)
  • UI state (ensuring valid screen states)
  • Frequent updates (like position coordinates)
  • Temporary values (like animation states)
  • Performance-critical code (validators add overhead)