Files
skills/docs/foundation/data/validation/src/schemas/number/number.md
2026-05-29 08:20:56 +01:00

2.6 KiB

NumberSchema

(no submodules)

Purpose

NumberSchema validates that an input is a JavaScript number and enforces numeric constraints. By default, NaN and Infinity are rejected (the finite check runs for all NumberSchema instances unless explicitly disabled). All constraint methods return new instances, preserving immutability across builder chains.

This schema covers the full range of server-side numeric validation: integer enforcement, range clamping, sign checks, and divisibility rules.

Features

  • Type check: rejects non-numbers with VALIDATION.INVALID_TYPE
  • Finite check by default: rejects NaN and Infinity with VALIDATION.NUMBER.NOT_FINITE
  • min(n) / max(n) — inclusive range
  • int() — integer-only (via Number.isInteger)
  • positive() — must be > 0
  • negative() — must be < 0
  • multipleOf(n) — divisibility check
  • finite() — explicit finite constraint (same as default)

Usage: Basic Example

import { number } from "@suaveplan/validation";

const age = number().int().min(0).max(150);
const result = age.safeParse(25);
// { success: true, data: 25 }

Usage: Advanced Example

import { number } from "@suaveplan/validation";

// Pagination offset: non-negative integer, multiple of 10
const offset = number().int().min(0).multipleOf(10);

// Latitude: float in range
const latitude = number().min(-90).max(90);

// Positive price with two-decimal precision (via multipleOf)
const cents = number().int().positive();

API Reference

number(): NumberSchema

Factory returning a NumberSchema with default finite enforcement.

Constraint methods (all return new NumberSchema)

Method Error code Description
min(n) NUMBER.TOO_SMALL Value must be ≥ n
max(n) NUMBER.TOO_LARGE Value must be ≤ n
int() NUMBER.NOT_INT Must be integer
positive() NUMBER.TOO_SMALL Must be > 0
negative() NUMBER.TOO_LARGE Must be < 0
multipleOf(n) NUMBER.NOT_MULTIPLE Must satisfy value % n === 0
finite() NUMBER.NOT_FINITE Must be finite (explicit)

Implementation Notes

  • The finite check runs first on every NumberSchema unless the finite constraint property is explicitly false. This prevents NaN from silently passing other checks.
  • positive() and negative() use strict inequality (0 is neither positive nor negative).
  • multipleOf uses the JavaScript modulo operator, which preserves sign for negative dividends — callers should be aware when combining with negative().