### Installation Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Install the JavaScript Object Sanitizer library using npm. ```APIDOC ## Installation ```bash npm install @asanrom/javascript-object-sanitizer ``` ``` -------------------------------- ### Install via NPM Source: https://github.com/agustinsrg/javascript-object-sanitizer/blob/master/README.md Use this command to install the package in an npm-managed project. ```bash npm install @asanrom/javascript-object-sanitizer ``` -------------------------------- ### ObjectSchema.object() - Define Object Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use ObjectSchema.object() to create a schema for objects with predefined properties. Unknown properties are automatically removed during sanitization. Includes examples for testing, sanitizing with defaults, and handling nested objects. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Object with defined properties const userSchema = ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), age: ObjectSchema.integer().withMin(0).withDefaultValue(0), email: ObjectSchema.string().withDefaultValue(""), isActive: ObjectSchema.boolean().withDefaultValue(false), }); // Test validation userSchema.test({ name: "John", age: 30, email: "john@example.com", isActive: true }); // true userSchema.test({ name: "John" }); // false (missing required properties) // Sanitize with defaults and type coercion userSchema.sanitize(null); // Result: { name: "", age: 0, email: "", isActive: false } userSchema.sanitize({ name: "Alice", age: "25", extra: "ignored" }); // Result: { name: "Alice", age: 25, email: "", isActive: false } ``` ```typescript // Nested objects const profileSchema = ObjectSchema.object({ user: ObjectSchema.object({ firstName: ObjectSchema.string().withDefaultValue(""), lastName: ObjectSchema.string().withDefaultValue(""), }), settings: ObjectSchema.object({ notifications: ObjectSchema.boolean().withDefaultValue(true), }), }); profileSchema.sanitize({ user: { firstName: "Jane" }, settings: null, }); // Result: { user: { firstName: "Jane", lastName: "" }, settings: { notifications: true } } ``` -------------------------------- ### Import via HTML script tag Source: https://github.com/agustinsrg/javascript-object-sanitizer/blob/master/README.md Include the library in a browser environment by importing the minified file. ```html ``` -------------------------------- ### test() and provideTestError() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Test schema compliance and retrieve detailed error messages for debugging. ```APIDOC ## test() and provideTestError() ### Description Test schema compliance and retrieve detailed error messages for debugging. ### Request Example ```typescript const userSchema = ObjectSchema.object({ username: ObjectSchema.string() }); const isValid = userSchema.test({ username: "john" }); const error = userSchema.provideTestError({ username: " " }); ``` ``` -------------------------------- ### Define and use schema in Browser Source: https://github.com/agustinsrg/javascript-object-sanitizer/blob/master/README.md Access the ObjectSchema from the global window object and apply it to validate or sanitize user input. ```javascript window.ObjectSchema = ObjectSanitizer.ObjectSchema; // Example schema or complex object const schema = ObjectSchema.object({ stringProperty: ObjectSchema.string().withDefaultValue(""), integerProperty: ObjectSchema.integer(), positiveNumber: ObjectSchema.number().withMin(0), array: ObjectSchema.array(ObjectSchema.object({ arrayItemProp1: ObjectSchema.boolean(), })), optionalProperty: ObjectSchema.optional(ObjectSchema.number()), }); // Test user input schema.test(userInput); // Returns true or false // Sanitize const sanitized = schema.sanitize(userInput); // Forces user input to follow the schema ``` -------------------------------- ### Number Schema with Min/Max Bounds Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a number schema with minimum and maximum bounds. Values outside these bounds are clamped to the nearest boundary. ```typescript // Number with min/max bounds (clamps to bounds) const percentSchema = ObjectSchema.number() .withMin(0) .withMax(100) .withDefaultValue(0); percentSchema.sanitize(50); // 50 percentSchema.sanitize(-10); // 0 (clamped to min) percentSchema.sanitize(150); // 100 (clamped to max) ``` -------------------------------- ### ObjectSchema.anyOf() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a union schema that accepts values matching any of the provided schemas. ```APIDOC ## ObjectSchema.anyOf() ### Description Creates a schema that accepts values matching any of the provided schemas. It supports a default schema to handle cases where none of the provided schemas match. ### Request Example ```typescript const stringOrIntSchema = ObjectSchema.anyOf([ ObjectSchema.integer(), ObjectSchema.string(), ]).withDefaultSchema(ObjectSchema.null()); ``` ``` -------------------------------- ### ObjectSchema.custom() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a schema with custom test and sanitize functions for complex validation logic. ```APIDOC ## ObjectSchema.custom() ### Description Creates a schema with custom test and sanitize functions for complex validation logic. ### Request Example ```typescript const dateSchema = ObjectSchema.custom() .withTester((obj) => obj instanceof Date) .withSanitizer((obj) => new Date(obj)); ``` ``` -------------------------------- ### ObjectSchema.extend() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Extends an existing schema with additional properties by referencing schema IDs. ```APIDOC ## ObjectSchema.extend() ### Description Extends an existing schema with additional properties by referencing schema IDs. ### Request Example ```typescript const personSchema = ObjectSchema.object({ name: ObjectSchema.string() }).withId("person"); const employeeSchema = ObjectSchema.extend(personSchema, { person: { age: ObjectSchema.integer() }, }); ``` ``` -------------------------------- ### Define Union Schemas Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Accepts values matching any of the provided schemas. Use withDefaultSchema to define a fallback for invalid inputs. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Accept either string or integer const stringOrIntSchema = ObjectSchema.anyOf([ ObjectSchema.integer(), ObjectSchema.string(), ]).withDefaultSchema(ObjectSchema.null()); stringOrIntSchema.test("hello"); // true stringOrIntSchema.test(42); // true stringOrIntSchema.test(3.14); // false (not integer) stringOrIntSchema.test(true); // false stringOrIntSchema.sanitize("hello"); // "hello" stringOrIntSchema.sanitize(42); // 42 stringOrIntSchema.sanitize(true); // null (default) stringOrIntSchema.sanitize([]); // null (default) // Union of different object types const responseSchema = ObjectSchema.anyOf([ ObjectSchema.object({ success: ObjectSchema.boolean().withEnumeration([true]), data: ObjectSchema.string().withDefaultValue(""), }), ObjectSchema.object({ success: ObjectSchema.boolean().withEnumeration([false]), error: ObjectSchema.string().withDefaultValue("Unknown error"), }), ]).withDefaultSchema(ObjectSchema.object({ success: ObjectSchema.boolean().withDefaultValue(false), error: ObjectSchema.string().withDefaultValue("Invalid response"), })); ``` -------------------------------- ### Define and use schema in Node.js Source: https://github.com/agustinsrg/javascript-object-sanitizer/blob/master/README.md Define a schema using ObjectSchema and apply it to validate or sanitize user input. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // With require: const ObjectSchema = require('@asanrom/javascript-object-sanitizer').ObjectSchema; // Example schema or complex object const schema = ObjectSchema.object({ stringProperty: ObjectSchema.string().withDefaultValue(""), integerProperty: ObjectSchema.integer(), positiveNumber: ObjectSchema.number().withMin(0), array: ObjectSchema.array(ObjectSchema.object({ arrayItemProp1: ObjectSchema.boolean(), })), optionalProperty: ObjectSchema.optional(ObjectSchema.number()), }); // Test user input schema.test(userInput); // Returns true or false // Sanitize const sanitized = schema.sanitize(userInput); // Forces user input to follow the schema ``` -------------------------------- ### Define and Use Schema for API Request/Response Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Demonstrates defining a complex nested schema for an API request body using ObjectSchema and then using test() and sanitize() methods. This is useful for validating and normalizing data from external sources. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Define request body schema const createOrderSchema = ObjectSchema.object({ customerId: ObjectSchema.string().withRegularExpression(/^[A-Z0-9]{8}$/).withDefaultValue(""), items: ObjectSchema.array( ObjectSchema.object({ productId: ObjectSchema.string().withDefaultValue(""), quantity: ObjectSchema.integer().withMin(1).withMax(100).withDefaultValue(1), price: ObjectSchema.number().withMin(0).withDefaultValue(0), }) ).withMaxLength(50).withDefaultValue([]), shippingAddress: ObjectSchema.object({ street: ObjectSchema.string().withMaxLength(200).withDefaultValue(""), city: ObjectSchema.string().withMaxLength(100).withDefaultValue(""), zipCode: ObjectSchema.string().withMaxLength(20).withDefaultValue(""), country: ObjectSchema.string().withEnumeration(["US", "CA", "UK", "DE", "FR"]).withDefaultValue("US"), }), notes: ObjectSchema.optional(ObjectSchema.string().withMaxLength(500)), priority: ObjectSchema.string().withEnumeration(["standard", "express", "overnight"]).withDefaultValue("standard"), }); // Express.js route handler example async function handleCreateOrder(req: Request, res: Response) { // Validate request body if (!createOrderSchema.test(req.body)) { const error = createOrderSchema.provideTestError(req.body); return res.status(400).json({ error: "Validation failed", details: error?.message }); } // Sanitize to ensure all values conform to schema const order = createOrderSchema.sanitize(req.body); // order is now guaranteed to have correct types and constraints: // - customerId matches pattern or is empty string // - items is an array with max 50 items // - each item has valid quantity (1-100) and price (>= 0) // - country is one of the allowed values // - notes is either a string or undefined console.log(order); // Process the validated order... } // Example input/output const rawInput = { customerId: "CUST1234", items: [ { productId: "SKU001", quantity: "5", price: 29.99 }, { productId: "SKU002", quantity: 200, price: -10 }, ], shippingAddress: { street: "123 Main St", city: "Boston", zipCode: "02101", country: "INVALID", }, notes: null, priority: "super-fast", extraField: "will be removed", }; const sanitized = createOrderSchema.sanitize(rawInput); // Result: // { // customerId: "CUST1234", // items: [ // { productId: "SKU001", quantity: 5, price: 29.99 }, // { productId: "SKU002", quantity: 100, price: 0 } // ], // shippingAddress: { // street: "123 Main St", // city: "Boston", // zipCode: "02101", // country: "US" // }, // notes: "", // priority: "standard" // } ``` -------------------------------- ### ObjectSchema.optional() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a schema that allows null or undefined values in addition to the base type, optionally falling back to a default value. ```APIDOC ## ObjectSchema.optional() ### Description Creates a schema that allows null/undefined values in addition to the base type. If the value is null or undefined, it can be sanitized to a default value provided by the inner schema. ### Request Example ```typescript const optionalNumberSchema = ObjectSchema.optional( ObjectSchema.number().withDefaultValue(0) ); optionalNumberSchema.sanitize(undefined); // Returns 0 ``` ``` -------------------------------- ### ObjectSchema.recursive() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates schemas for self-referential structures like trees using ID references. ```APIDOC ## ObjectSchema.recursive() ### Description Creates schemas for self-referential structures like trees using ID references. Supports limiting recursion depth via withMaxRecursion. ### Request Example ```typescript const treeNodeSchema = ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), childA: ObjectSchema.optional(ObjectSchema.recursive().withReference("node")), }).withId("node"); ``` ``` -------------------------------- ### String Schema with Max Length Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a string schema that enforces a maximum length. Input strings exceeding this length are truncated. ```typescript // String with max length (truncates if exceeded) const maxLengthSchema = ObjectSchema.string().withMaxLength(5); maxLengthSchema.sanitize("hello world"); // "hello" ``` -------------------------------- ### ObjectSchema.number() - Number Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a schema for number validation, supporting integer forcing, min/max bounds, NaN/Infinity handling, and enumerations. ```APIDOC ## ObjectSchema.number() - Number Schema Creates a schema for number validation with support for integer forcing, min/max bounds, NaN/Infinity handling, and enumeration. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Basic number schema with default value const numberSchema = ObjectSchema.number().withDefaultValue(0); numberSchema.test(42); // true numberSchema.test("42"); // false numberSchema.sanitize(42); // 42 numberSchema.sanitize("42"); // 42 (parsed from string) numberSchema.sanitize(null); // 0 (default value) // Number with min/max bounds (clamps to bounds) const percentSchema = ObjectSchema.number() .withMin(0) .withMax(100) .withDefaultValue(0); percentSchema.sanitize(50); // 50 percentSchema.sanitize(-10); // 0 (clamped to min) percentSchema.sanitize(150); // 100 (clamped to max) // Integer schema (truncates decimals) const intSchema = ObjectSchema.integer().withDefaultValue(0); intSchema.test(5); // true intSchema.test(5.5); // false intSchema.sanitize(5.9); // 5 (truncated) // Allow NaN and Infinity (disabled by default) const specialNumberSchema = ObjectSchema.number() .allowNaN() .allowInfinite(); specialNumberSchema.sanitize(NaN); // NaN specialNumberSchema.sanitize(Infinity); // Infinity // Number with enumeration const prioritySchema = ObjectSchema.number() .withEnumeration([1, 2, 3]) .withDefaultValue(1); prioritySchema.sanitize(2); // 2 prioritySchema.sanitize(5); // 1 (default, not in enumeration) ``` ``` -------------------------------- ### ObjectSchema.object() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a schema for object validation with defined properties. Unknown properties are stripped during sanitization. ```APIDOC ## ObjectSchema.object() ### Description Creates a schema for object validation with defined properties. Unknown properties are stripped during sanitization. ### Request Example ```typescript const userSchema = ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), age: ObjectSchema.integer().withMin(0).withDefaultValue(0), email: ObjectSchema.string().withDefaultValue(""), isActive: ObjectSchema.boolean().withDefaultValue(false), }); ``` ``` -------------------------------- ### ObjectSchema.string() - String Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a schema for string validation with support for default values, maximum length, regular expressions, and enumerations. ```APIDOC ## ObjectSchema.string() - String Schema Creates a schema for string validation with optional constraints including default values, max length, regular expression matching, and enumeration restrictions. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Basic string schema with default value const stringSchema = ObjectSchema.string().withDefaultValue(""); stringSchema.test("hello"); // true stringSchema.test(123); // false stringSchema.sanitize("hello"); // "hello" stringSchema.sanitize(null); // "" stringSchema.sanitize(123); // "123" (type coercion) stringSchema.sanitize(new Date()); // "2024-01-15T10:30:00.000Z" (ISO string) // String with max length (truncates if exceeded) const maxLengthSchema = ObjectSchema.string().withMaxLength(5); maxLengthSchema.sanitize("hello world"); // "hello" // String with regular expression validation const emailSchema = ObjectSchema.string() .withRegularExpression(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) .withDefaultValue("invalid@example.com"); emailSchema.sanitize("user@domain.com"); // "user@domain.com" emailSchema.sanitize("invalid-email"); // "invalid@example.com" // String with enumeration const statusSchema = ObjectSchema.string() .withEnumeration(["pending", "active", "completed"]) .withDefaultValue("pending"); statusSchema.sanitize("active"); // "active" statusSchema.sanitize("unknown"); // "pending" ``` ``` -------------------------------- ### Validate Data with test() and provideTestError() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use the test() method to check if an object conforms to a schema, returning a boolean. For failed validations, provideTestError() returns a detailed error object for debugging. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; const userSchema = ObjectSchema.object({ username: ObjectSchema.string().withRegularExpression(/^[a-z0-9_]+$/i), email: ObjectSchema.string(), age: ObjectSchema.integer().withMin(18).withMax(120), }); // Test returns boolean userSchema.test({ username: "john_doe", email: "john@example.com", age: 25 }); // true userSchema.test({ username: "john doe", email: "john@example.com", age: 25 }); // false // Get detailed error for failed validation const invalidUser = { username: "john doe", email: "john@example.com", age: 15 }; const error = userSchema.provideTestError(invalidUser); console.log(error.message); // "String does not match regular expession: john doe" // Error debugging in API handler function validateRequest(body: unknown) { if (!userSchema.test(body)) { const error = userSchema.provideTestError(body); throw new Error(`Validation failed: ${error?.message}`); } return userSchema.sanitize(body); } ``` -------------------------------- ### ObjectSchema.dict() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a schema for dictionary objects with dynamic keys validated by a filter function. ```APIDOC ## ObjectSchema.dict() ### Description Creates a schema for dictionary objects with dynamic keys validated by a filter function. Keys not matching the filter are stripped. ### Request Example ```typescript const dynamicSchema = ObjectSchema.dict( (key) => /^prop[0-9]+$/.test(key), () => ObjectSchema.string().withDefaultValue("") ); ``` ``` -------------------------------- ### ObjectSchema.array() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a schema for array validation with item schema and optional length constraints. ```APIDOC ## ObjectSchema.array() ### Description Creates a schema for array validation with item schema and optional length constraints. Supports truncation and filtering of invalid items. ### Request Example ```typescript const tagsSchema = ObjectSchema.array(ObjectSchema.string()) .withDefaultValue([]); ``` ``` -------------------------------- ### String Schema with Default Value Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a basic string schema with a default empty string. It tests string inputs and sanitizes various types, including null and numbers, to strings. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Basic string schema with default value const stringSchema = ObjectSchema.string().withDefaultValue(""); stringSchema.test("hello"); // true stringSchema.test(123); // false stringSchema.sanitize("hello"); // "hello" stringSchema.sanitize(null); // "" stringSchema.sanitize(123); // "123" (type coercion) stringSchema.sanitize(new Date()); // "2024-01-15T10:30:00.000Z" (ISO string) ``` -------------------------------- ### Create Custom Schemas with ObjectSchema.custom() Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use ObjectSchema.custom to define schemas with custom testing and sanitization logic. This is ideal for complex data types or validation rules not covered by built-in types. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Custom date validation const dateSchema = ObjectSchema.custom() .withTester((obj) => obj instanceof Date && !isNaN(obj.getTime())) .withSanitizer((obj) => { if (obj instanceof Date && !isNaN(obj.getTime())) { return obj; } const parsed = new Date(obj); return isNaN(parsed.getTime()) ? new Date() : parsed; }); dateSchema.test(new Date()); // true dateSchema.test("2024-01-15"); // false dateSchema.sanitize("2024-01-15"); // Date object for 2024-01-15 dateSchema.sanitize("invalid"); // Current date (fallback) ``` ```typescript // Custom UUID validation const uuidSchema = ObjectSchema.custom() .withTester((obj) => typeof obj === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(obj) ) .withSanitizer((obj) => { if (typeof obj === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(obj)) { return obj.toLowerCase(); } return "00000000-0000-0000-0000-000000000000"; }); uuidSchema.sanitize("550E8400-E29B-41D4-A716-446655440000"); // Result: "550e8400-e29b-41d4-a716-446655440000" ``` -------------------------------- ### String Schema with Enumeration Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a string schema that restricts values to a predefined enumeration. Values not in the list revert to the default. ```typescript // String with enumeration const statusSchema = ObjectSchema.string() .withEnumeration(["pending", "active", "completed"]) .withDefaultValue("pending"); statusSchema.sanitize("active"); // "active" statusSchema.sanitize("unknown"); // "pending" ``` -------------------------------- ### Define Optional Schemas Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Allows null or undefined values for a schema. When sanitizing, it falls back to the inner schema's default value if provided. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Optional number property const optionalNumberSchema = ObjectSchema.optional( ObjectSchema.number().withDefaultValue(0) ); optionalNumberSchema.test(42); // true optionalNumberSchema.test(undefined); // true optionalNumberSchema.test(null); // true optionalNumberSchema.test("42"); // false optionalNumberSchema.sanitize(42); // 42 optionalNumberSchema.sanitize(undefined); // 0 (uses inner schema default) optionalNumberSchema.sanitize(null); // 0 // Object with optional properties const configSchema = ObjectSchema.object({ host: ObjectSchema.string().withDefaultValue("localhost"), port: ObjectSchema.integer().withDefaultValue(8080), timeout: ObjectSchema.optional(ObjectSchema.integer().withMin(0)), retries: ObjectSchema.optional(ObjectSchema.integer().withMin(0)), }); configSchema.sanitize({ host: "example.com" }); // Result: { host: "example.com", port: 8080, timeout: 0, retries: 0 } ``` -------------------------------- ### ObjectSchema.array() - Define Array Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use ObjectSchema.array() to create schemas for arrays. Specify the schema for array items and optionally set default values, maximum length, or use enumeration filtering. Invalid items are removed or filtered out. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Array of strings const tagsSchema = ObjectSchema.array(ObjectSchema.string()) .withDefaultValue([]); tagsSchema.test(["a", "b", "c"]); // true tagsSchema.test([1, 2, 3]); // false (items must be strings) tagsSchema.sanitize(null); // [] tagsSchema.sanitize(["a", "b"]); // ["a", "b"] ``` ```typescript // Array with max length (truncates if exceeded) const limitedArraySchema = ObjectSchema.array(ObjectSchema.integer()) .withMaxLength(3) .withDefaultValue([]); limitedArraySchema.sanitize([1, 2, 3, 4, 5]); // [1, 2, 3] ``` ```typescript // Array of objects const itemsSchema = ObjectSchema.array( ObjectSchema.object({ id: ObjectSchema.integer().withDefaultValue(0), name: ObjectSchema.string().withDefaultValue(""), price: ObjectSchema.number().withMin(0).withDefaultValue(0), }) ).withDefaultValue([]); itemsSchema.sanitize([ { id: 1, name: "Item A", price: 9.99 }, { id: "2", name: "Item B" }, null, ]); // Result: [ // { id: 1, name: "Item A", price: 9.99 }, // { id: 2, name: "Item B", price: 0 }, // { id: 0, name: "", price: 0 } // ] ``` ```typescript // Array with enumeration filtering (invalid items removed) const statusArraySchema = ObjectSchema.array( ObjectSchema.string().withEnumeration(["pending", "active", "done"]) ); statusArraySchema.sanitize(["pending", "invalid", "active", "unknown"]); // Result: ["pending", "active"] (invalid values filtered out) ``` -------------------------------- ### Number Schema Allowing NaN and Infinity Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Configures a number schema to accept NaN and Infinity values. These are disallowed by default. ```typescript // Allow NaN and Infinity (disabled by default) const specialNumberSchema = ObjectSchema.number() .allowNaN() .allowInfinite(); specialNumberSchema.sanitize(NaN); // NaN specialNumberSchema.sanitize(Infinity); // Infinity ``` -------------------------------- ### Number Schema with Enumeration Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a number schema that restricts values to a specific set of numbers. Non-conforming numbers revert to the default value. ```typescript // Number with enumeration const prioritySchema = ObjectSchema.number() .withEnumeration([1, 2, 3]) .withDefaultValue(1); prioritySchema.sanitize(2); // 2 prioritySchema.sanitize(5); // 1 (default, not in enumeration) ``` -------------------------------- ### String Schema with Regular Expression Validation Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a string schema that validates input against a regular expression for email format. Invalid inputs are replaced with a default value. ```typescript // String with regular expression validation const emailSchema = ObjectSchema.string() .withRegularExpression(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) .withDefaultValue("invalid@example.com"); emailSchema.sanitize("user@domain.com"); // "user@domain.com" emailSchema.sanitize("invalid-email"); // "invalid@example.com" ``` -------------------------------- ### ObjectSchema.dict() - Define Dictionary Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use ObjectSchema.dict() to create schemas for dictionaries with dynamic keys. A key filter function and an item schema (or a function to generate it based on the key) are required. Invalid keys are stripped during sanitization. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Dictionary where keys must match pattern "prop" followed by numbers const dynamicSchema = ObjectSchema.dict( (key) => /^prop[0-9]+$/.test(key), () => ObjectSchema.string().withDefaultValue("") ); dynamicSchema.test({ prop1: "a", prop2: "b" }); // true dynamicSchema.test({ random: "value" }); // false (key doesn't match filter) dynamicSchema.sanitize({ prop1: "a", prop2: "b", invalid: "c" }); // Result: { prop1: "a", prop2: "b" } (invalid key stripped) ``` ```typescript // Dictionary with schema based on key const configSchema = ObjectSchema.dict( (key) => key.startsWith("config_"), (key) => key.endsWith("_count") ? ObjectSchema.integer().withDefaultValue(0) : ObjectSchema.string().withDefaultValue("") ); configSchema.sanitize({ config_name: "app", config_items_count: "10", config_enabled: "true", }); // Result: { config_name: "app", config_items_count: 10, config_enabled: "true" } ``` -------------------------------- ### Number Schema with Default Value Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a basic number schema with a default value of 0. It tests numeric inputs and sanitizes strings and null values. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Basic number schema with default value const numberSchema = ObjectSchema.number().withDefaultValue(0); numberSchema.test(42); // true numberSchema.test("42"); // false numberSchema.sanitize(42); // 42 numberSchema.sanitize("42"); // 42 (parsed from string) numberSchema.sanitize(null); // 0 (default value) ``` -------------------------------- ### Boolean Schema with Default Value Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a basic boolean schema with a default value of false. It sanitizes truthy/falsy values and null. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; const boolSchema = ObjectSchema.boolean().withDefaultValue(false); boolSchema.test(true); // true boolSchema.test(false); // true boolSchema.test("true"); // false boolSchema.sanitize(true); // true boolSchema.sanitize(false); // false boolSchema.sanitize(1); // true (truthy coercion) boolSchema.sanitize(0); // false (falsy coercion) boolSchema.sanitize(null); // false (default value) ``` -------------------------------- ### ObjectSchema.boolean() - Boolean Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a schema for boolean validation, including type coercion and optional default values. ```APIDOC ## ObjectSchema.boolean() - Boolean Schema Creates a schema for boolean validation with type coercion and optional default values. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; const boolSchema = ObjectSchema.boolean().withDefaultValue(false); boolSchema.test(true); // true boolSchema.test(false); // true boolSchema.test("true"); // false boolSchema.sanitize(true); // true boolSchema.sanitize(false); // false boolSchema.sanitize(1); // true (truthy coercion) boolSchema.sanitize(0); // false (falsy coercion) boolSchema.sanitize(null); // false (default value) // Boolean with enumeration (force specific value) const alwaysTrueSchema = ObjectSchema.boolean() .withEnumeration([true]) .withDefaultValue(true); alwaysTrueSchema.sanitize(false); // true ``` ``` -------------------------------- ### Extend ObjectSchema with Additional Properties Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Use ObjectSchema.extend to add new properties to an existing schema by referencing schema IDs. This is useful for building complex schemas from smaller, reusable parts. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Base schema with ID const personSchema = ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), surname: ObjectSchema.string().withDefaultValue(""), }).withId("person"); // Extend the schema with new properties const employeeSchema = ObjectSchema.extend(personSchema, { person: { age: ObjectSchema.integer().withMin(0).withDefaultValue(0), department: ObjectSchema.string().withDefaultValue(""), }, }); personSchema.test({ name: "John", surname: "Doe" }); // true employeeSchema.test({ name: "John", surname: "Doe" }); // false (missing new props) employeeSchema.test({ name: "John", surname: "Doe", age: 30, department: "IT" }); // true employeeSchema.sanitize({ name: "John", surname: "Doe" }); // Result: { name: "John", surname: "Doe", age: 0, department: "" } ``` ```typescript // Extend nested schemas const companySchema = ObjectSchema.object({ person: ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), }).withId("person"), }).withId("root"); const extendedCompanySchema = ObjectSchema.extend(companySchema, { person: { title: ObjectSchema.string().withDefaultValue(""), }, }); extendedCompanySchema.sanitize({ person: { name: "Jane" } }); // Result: { person: { name: "Jane", title: "" } } ``` -------------------------------- ### Integer Schema Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Defines a schema for integers, truncating any decimal part of a number during sanitization. Includes a default value. ```typescript // Integer schema (truncates decimals) const intSchema = ObjectSchema.integer().withDefaultValue(0); intSchema.test(5); // true intSchema.test(5.5); // false intSchema.sanitize(5.9); // 5 (truncated) ``` -------------------------------- ### Boolean Schema with Enumeration Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Creates a boolean schema that forces a specific boolean value, overriding any input. Useful for ensuring a value is always true. ```typescript // Boolean with enumeration (force specific value) const alwaysTrueSchema = ObjectSchema.boolean() .withEnumeration([true]) .withDefaultValue(true); alwaysTrueSchema.sanitize(false); // true ``` -------------------------------- ### Define Recursive Schemas Source: https://context7.com/agustinsrg/javascript-object-sanitizer/llms.txt Enables self-referential structures using ID references. Supports limiting recursion depth to prevent stack overflows or excessive nesting. ```typescript import { ObjectSchema } from '@asanrom/javascript-object-sanitizer'; // Tree node with recursive children const treeNodeSchema = ObjectSchema.object({ name: ObjectSchema.string().withDefaultValue(""), childA: ObjectSchema.optional(ObjectSchema.recursive().withReference("node")), childB: ObjectSchema.optional(ObjectSchema.recursive().withReference("node")), }).withId("node"); // Test nested structure treeNodeSchema.test({ name: "root", childA: { name: "child1", childB: { name: "grandchild" }, }, }); // true // Sanitize recursive structure treeNodeSchema.sanitize({ name: "root", childA: { name: "child1" }, childB: true, // invalid, will be sanitized to default object }); // Result: { // name: "root", // childA: { name: "child1" }, // childB: { name: "" } // } // Limit recursion depth const limitedTreeSchema = ObjectSchema.object({ value: ObjectSchema.integer().withDefaultValue(0), child: ObjectSchema.optional( ObjectSchema.recursive().withReference("node").withMaxRecursion(2) ), }).withId("node"); // Deep nesting beyond maxRecursion is stripped limitedTreeSchema.sanitize({ value: 1, child: { value: 2, child: { value: 3, child: { value: 4 }, // This level will be removed }, }, }); // Result: { value: 1, child: { value: 2, child: { value: 3 } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.