Skip to main content

Type Alias: SchemaValidator()<T>

SchemaValidator<T>: (value) => ValidationResult & object

Defined in: src/types/validation.ts:184

Schema validator with detailed error reporting.

Type Parameters

T

Type to validate

Parameters

value

unknown

Returns

ValidationResult & object

Remarks

A validator function that returns a ValidationResult with detailed error messages for each field. If validation succeeds, the result includes the validated value.

Use this for complex validation scenarios where you need to report multiple errors to users.

Example

interface User {
name: string;
email: string;
age: number;
}

const validateUser: SchemaValidator<User> = (value) => {
const errors: FieldValidationResult[] = [];

if (typeof value !== 'object' || value === null) {
return { valid: false, errors: [{ field: 'root', valid: false, errors: ['Value must be an object'] }] };
}

const obj = value as Record<string, unknown>;

if (typeof obj.name !== 'string' || obj.name.length === 0) {
errors.push({ field: 'name', valid: false, errors: ['Name is required'] });
}

if (typeof obj.email !== 'string' || !obj.email.includes('@')) {
errors.push({ field: 'email', valid: false, errors: ['Email must be valid'] });
}

if (typeof obj.age !== 'number' || obj.age < 0) {
errors.push({ field: 'age', valid: false, errors: ['Age must be a positive number'] });
}

if (errors.length > 0) {
return { valid: false, errors };
}

return {
valid: true,
errors: [],
value: obj as User
};
};