# LightJx AI Developer Guidance This comprehensive guide provides everything an AI developer needs to become proficient with LightJx validation framework. LightJx is a fluent JavaScript validation library that works in both browser and Node.js environments. ## Table of Contents 1. [Quick Start](#quick-start) 2. [Core Concepts](#core-concepts) 3. [Usage Patterns](#usage-patterns) 4. [Complete Validator Reference](#complete-validator-reference) 5. [Implementation Examples](#implementation-examples) 6. [Best Practices](#best-practices) ## Quick Start ### Installation ```bash npm install lightjx ``` ### Basic Usage ```javascript import { Validate } from 'lightjx'; // Define a validator const emailValidator = Validate.field("email", "Email Address") .required() .asEmail(); // Validate input const result = emailValidator.validate("user@example.com"); if (!result.isValid) { console.log(result.errorMessage); // "Email Address is required" } ``` ## Core Concepts ### Fluent API LightJx uses method chaining to build validation rules: ```javascript Validate.field("username", "Username") .required() .asAlphaNumericText() .hasMinLength(3) .hasMaxLength(20) ``` ### Two Entry Points 1. **Named Fields**: Use when you have a specific field to validate ```javascript Validate.field("fieldName", "Display Name") ``` 2. **Anonymous Validation**: Use for general-purpose validation ```javascript Validate.define() ``` ### Validation Result Structure ```javascript { isValid: boolean, errorMessage: string, // Combined error messages errorMessages: string[], // Array of all errors input: any // The validated input } ``` ### Important Behaviors - Most validators **succeed on empty values** (null, undefined, "") unless `.required()` is used - Validators can accept **functions** for dynamic values - Error messages automatically include field display names - Multiple validators are executed in order, collecting all errors ## Usage Patterns ### Pattern 1: Direct Fluent API ```javascript // Inline validation const isValid = Validate.field("age", "Age") .required() .asNumber() .min(18) .max(120) .validate(25) .isValid; ``` ### Pattern 2: Reusable Validators ```javascript // Define once, use multiple times const passwordValidator = Validate.field("password", "Password") .required() .hasMinLength(8) .containsText(/[A-Z]/) // At least one uppercase .containsText(/[0-9]/); // At least one number // Use repeatedly passwordValidator.validate("Pass123!"); // true passwordValidator.validate("weak"); // false ``` ### Pattern 3: Form Validation Object ```javascript const validators = { username: Validate.field("username", "Username").required().asAlphaNumericText(), email: Validate.field("email", "Email").required().asEmail(), age: Validate.field("age", "Age").required().asNumber().min(18) }; // Validate form data function validateForm(formData) { const errors = {}; for (const [field, validator] of Object.entries(validators)) { const result = validator.validate(formData[field]); if (!result.isValid) { errors[field] = result.errorMessage; } } return errors; } ``` ### Pattern 4: Dynamic Validation ```javascript // Using functions for runtime values const dateValidator = Validate.field("startDate", "Start Date") .required() .asDate() .isDateOnOrAfter(() => new Date()); // Function executed at validation time // Dynamic min/max const priceValidator = Validate.field("price", "Price") .required() .asNumber() .min(() => getMinPrice()) .max(() => getMaxPrice()); ``` ## Complete Validator Reference ### Text Validators #### asAlphaText() Validates alphabetic characters and spaces only. ```javascript Validate.field("name", "Name").asAlphaText() // Valid: "John Doe", "ABC", "Test Name" // Invalid: "John123", "Test-Name", "user@email" ``` #### asAlphaNumericText() Validates alphanumeric characters only (no spaces). ```javascript Validate.field("code", "Code").asAlphaNumericText() // Valid: "ABC123", "test", "123" // Invalid: "ABC 123", "test-code", "user@123" ``` #### asAlphaNumericHyphenText() Validates alphanumeric characters, spaces, and hyphens. ```javascript Validate.field("slug", "Slug").asAlphaNumericHyphenText() // Valid: "my-slug-123", "ABC 123", "test-name" // Invalid: "test@name", "slug#123", "name!" ``` #### asName() Validates names (letters, spaces, hyphens, apostrophes). ```javascript Validate.field("fullName", "Full Name").asName() // Valid: "John O'Brien", "Mary-Jane", "José" // Invalid: "John123", "Name@test", "User#1" ``` ### Email & URL Validators #### asEmail() Validates email addresses. ```javascript Validate.field("email", "Email").asEmail() // Valid: "user@example.com", "test.user+tag@domain.co.uk" // Invalid: "notanemail", "@example.com", "user@" ``` #### asUrl() Validates URLs (http, https, mailto, news). ```javascript Validate.field("website", "Website").asUrl() // Valid: "https://example.com", "http://test.org", "mailto:user@example.com" // Invalid: "example.com", "ftp://file.com", "not a url" ``` #### asSecureUrl() Validates HTTPS URLs only. ```javascript Validate.field("apiEndpoint", "API Endpoint").asSecureUrl() // Valid: "https://api.example.com", "https://secure.test.org" // Invalid: "http://example.com", "ftp://file.com", "example.com" ``` ### Number Validators #### asNumber() Validates numeric values (accepts number type or numeric strings). ```javascript Validate.field("quantity", "Quantity").asNumber() // Valid: 123, "456", -789, "12.34" // Invalid: "abc", "12a", null (without required) ``` #### asInt() Validates integers only. ```javascript Validate.field("count", "Count").asInt() // Valid: 123, "456", -789, "0" // Invalid: 12.34, "12.34", "abc", "1.0" ``` #### asFloat() Validates floating-point numbers. ```javascript Validate.field("price", "Price").asFloat() // Valid: 12.34, "56.78", 100, "0.5" // Invalid: "abc", "12.34.56", "1,234.56" ``` #### min(value) Sets minimum value (works with numbers). ```javascript Validate.field("age", "Age").asNumber().min(18) // Valid: 18, 19, 100, "25" // Invalid: 17, "10", -5 // With function Validate.field("price", "Price").asNumber().min(() => getMinPrice()) ``` #### max(value) Sets maximum value (works with numbers). ```javascript Validate.field("percentage", "Percentage").asNumber().max(100) // Valid: 0, 50, 100, "99.9" // Invalid: 101, "150", 200 // With function Validate.field("quantity", "Quantity").asNumber().max(() => getStock()) ``` ### Date Validators #### asDate() Validates date objects or ISO date strings. ```javascript Validate.field("birthDate", "Birth Date").asDate() // Valid: new Date(), "2023-12-25", "2023-01-01T00:00:00Z" // Invalid: "invalid-date", "25/12/2023", "December 25, 2023" ``` #### isDateOnOrAfter(date) Validates date is on or after specified date. ```javascript const today = new Date(); Validate.field("startDate", "Start Date").isDateOnOrAfter(today) // Valid: today, tomorrow, future dates // Invalid: yesterday, past dates // With function Validate.field("endDate", "End Date").isDateOnOrAfter(() => getStartDate()) ``` #### isDateOnOrBefore(date) Validates date is on or before specified date. ```javascript const deadline = new Date('2024-12-31'); Validate.field("submitDate", "Submit Date").isDateOnOrBefore(deadline) // Valid: today, deadline, past dates // Invalid: dates after deadline // With function Validate.field("startDate", "Start Date").isDateOnOrBefore(() => getEndDate()) ``` #### isDateBetween(minDate, maxDate) Validates date is between two dates (inclusive). ```javascript const start = new Date('2024-01-01'); const end = new Date('2024-12-31'); Validate.field("eventDate", "Event Date").isDateBetween(start, end) // Valid: any date in 2024 // Invalid: dates before 2024 or after 2024 ``` ### String Length Validators #### hasMinLength(length) Validates minimum string length. ```javascript Validate.field("username", "Username").hasMinLength(3) // Valid: "abc", "username", "test123" // Invalid: "ab", "a", "" // With function Validate.field("code", "Code").hasMinLength(() => getMinCodeLength()) ``` #### hasMaxLength(length) Validates maximum string length. ```javascript Validate.field("tweet", "Tweet").hasMaxLength(280) // Valid: any string up to 280 characters // Invalid: strings longer than 280 characters // With function Validate.field("comment", "Comment").hasMaxLength(() => getMaxCommentLength()) ``` #### hasLengthRange(min, max) Validates string length within range. ```javascript Validate.field("password", "Password").hasLengthRange(8, 20) // Valid: "password123" (11 chars), "securepass" (10 chars) // Invalid: "short" (5 chars), "verylongpasswordthatexceedslimit" (32 chars) ``` #### hasLength(length) Validates exact string length. Useful for postal codes, IDs, phone numbers, and any field requiring specific character counts. ```javascript // US Zip Code validation Validate.field("zipCode", "Zip Code").hasLength(5) // Valid: "12345", "90210", "54321" // Invalid: "1234", "123456", "abc12" // UK Postal Code (first part) Validate.field("postalCode", "Postal Code").hasLength(4).asAlphaNumericText() // Valid: "SW1A", "M1 1A", "B33 8TH" (first 4 chars) // Invalid: "SW1", "SW1AB1", "12345" // Product SKU validation Validate.field("sku", "SKU").hasLength(8).asAlphaNumericText() // Valid: "ABC12345", "XYZ98765", "12345678" // Invalid: "ABC123", "ABC123456", "ABC-1234" // Works with numbers (converted to string length) Validate.field("employeeId", "Employee ID").hasLength(6) // Valid: 123456, "654321", "000001" // Invalid: 12345, 1234567, "abc123" // Works with arrays (validates array length) Validate.field("coordinates", "Coordinates").hasLength(2) // Valid: [10, 20], ["lat", "lng"] // Invalid: [10], [10, 20, 30] // Dynamic length with function Validate.field("securityCode", "Security Code").hasLength(() => getRequiredCodeLength()) // Function called at validation time // Combined with other validators Validate.field("productCode", "Product Code") .required() .hasLength(10) .asAlphaNumericHyphenText() // Must be exactly 10 characters, alphanumeric with hyphens allowed ``` ### Content Validators #### required() Makes field required (must have a value). ```javascript Validate.field("name", "Name").required() // Valid: "any value", 0, false, " " (space) // Invalid: null, undefined, "", NaN ``` #### asBoolean() Validates boolean values. ```javascript Validate.field("agreed", "Agreement").asBoolean() // Valid: true, false, "true", "false" // Invalid: "yes", "no", 1, 0, "1" ``` #### containsText(text, ignoreCase) Validates string contains specific text. ```javascript Validate.field("description", "Description").containsText("important") // Valid: "This is important", "important notice" // Invalid: "This is not", "IMPORTANT" (case sensitive) // Case insensitive Validate.field("content", "Content").containsText("warning", true) // Valid: "Warning!", "WARNING", "wArNiNg" // With function Validate.field("message", "Message").containsText(() => getRequiredKeyword()) ``` #### doesNotContainText(text, ignoreCase) Validates string does not contain specific text. ```javascript Validate.field("username", "Username").doesNotContainText("admin") // Valid: "user123", "john_doe" // Invalid: "administrator", "admin_user" // Case insensitive Validate.field("comment", "Comment").doesNotContainText("spam", true) // Valid: "Great post!", "Thanks" // Invalid: "SPAM", "This is spam", "SpAm" ``` #### hasNoBrackets() Prevents angle brackets (basic XSS prevention). ```javascript Validate.field("comment", "Comment").hasNoBrackets() // Valid: "This is safe text", "No HTML here" // Invalid: "