Skip to main content

Validation

The Validation module provides schema-based data validation using a fluent API. It is used internally by all wires to validate REST API request bodies and can be used directly in your application code.

Usage

import { FluxKit, Schema } from "@fluxkitdev/core";

const app = new FluxKit({
database: { uri: process.env.MONGODB_URI },
});

// Define a schema
const userSchema = Schema.object({
email: Schema.string().email().required(),
name: Schema.string().min(2).max(100).required(),
age: Schema.number().min(0).max(150).optional(),
role: Schema.string().oneOf(["admin", "user"]).default("user"),
});

// Validate data
const result = app.validator.validate(userSchema, {
email: "alice@example.com",
name: "Alice",
age: 30,
});

if (result.valid) {
console.log(result.data); // Typed and sanitized data
} else {
console.log(result.errors); // Array of validation errors
}

API Reference

Schema Types

Schema.string()

Schema.string()
.min(1) // Minimum length
.max(255) // Maximum length
.email() // Must be a valid email
.url() // Must be a valid URL
.pattern(/^[a-z]+$/) // Must match regex
.oneOf(["a", "b"]) // Must be one of the values
.required() // Cannot be undefined or null
.optional() // Can be undefined
.default("value") // Default if undefined

Schema.number()

Schema.number()
.min(0) // Minimum value
.max(100) // Maximum value
.integer() // Must be an integer
.positive() // Must be > 0
.required()

Schema.boolean()

Schema.boolean()
.required()
.default(false)

Schema.object(shape)

Schema.object({
name: Schema.string().required(),
nested: Schema.object({
field: Schema.number(),
}),
})

Schema.array(itemSchema)

Schema.array(Schema.string().email())
.min(1) // Minimum items
.max(10) // Maximum items

validator.validate(schema, data): ValidationResult

Validates data against a schema. Returns an object with:

  • valid: boolean -- Whether validation passed
  • data: T -- The validated and sanitized data (only when valid)
  • errors: ValidationError[] -- Array of errors (only when invalid)

validator.assert(schema, data): T

Like validate, but throws an error if validation fails.

try {
const user = app.validator.assert(userSchema, input);
// user is typed and validated
} catch (err) {
// ValidationError with details
}

Middleware

The validator integrates with the HTTP middleware to automatically validate request bodies:

import { Schema } from "@fluxkitdev/core";

app.http.post("/users", {
body: Schema.object({
email: Schema.string().email().required(),
name: Schema.string().required(),
}),
handler: async (req, res) => {
// req.body is already validated and typed
const { email, name } = req.body;
},
});