### Install fluentvalidation-ts with NPM Source: https://fluentvalidation-ts.alexpotter.dev/docs/overview Installs the fluentvalidation-ts library using npm. This is the recommended method for Node.js environments and modern front-end projects. ```bash npm install fluentvalidation-ts --save ``` -------------------------------- ### Install fluentvalidation-ts with Yarn Source: https://fluentvalidation-ts.alexpotter.dev/docs/overview Installs the fluentvalidation-ts library using Yarn. This is an alternative package manager for Node.js projects. ```bash yarn add fluentvalidation-ts ``` -------------------------------- ### FluentValidation `.notEmpty()` Rule Example (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/notEmpty Demonstrates how to use the `.notEmpty()` rule in fluentvalidation-ts to validate a string property. This rule ensures the string is neither an empty string nor contains only whitespace characters. It includes examples of successful validation and validation failure. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty(); } } const formValidator = new FormValidator(); formValidator.validate({ name: 'Alex' }); // ✔ {} formValidator.validate({ name: ' ' }); // ❌ { name: 'Value cannot be empty' } ``` -------------------------------- ### FluentValidation TS: Enforce Strict Equality with .equal() Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/equal This example demonstrates how to use the `.equal()` rule in FluentValidation TS to validate if a boolean property strictly matches a specified value (true in this case). It shows the validator setup and the results of validating both true and false inputs. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { acceptsTermsAndConditions: boolean; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('acceptsTermsAndConditions').equal(true); } } const formValidator = new FormValidator(); formValidator.validate({ acceptsTermsAndConditions: true }); // ✔ {} formValidator.validate({ acceptsTermsAndConditions: false }); // ❌ { acceptsTermsAndConditions: `Must equal 'true'` } ``` -------------------------------- ### Validate Form Models with Transformed Age Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Provides examples of validating different `FormModel` instances with the `age` property set to valid, negative, and non-numeric string values, showcasing the output of the `validate` method after transformation. ```typescript const valid: FormModel = { name: 'Alex', age: '26', hasPet: true, pet: { name: 'Doggy', species: 'Dog' }, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(valid)); const invalid1: FormModel = { name: 'Alex', age: '-10', hasPet: true, pet: { name: 'Doggy', species: 'Dog' }, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(invalid1)); const invalid2: FormModel = { name: 'Alex', age: 'foo', hasPet: true, pet: { name: 'Doggy', species: 'Dog' }, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(invalid2)); ``` -------------------------------- ### Test Conditional Validation (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Provides examples of validating form models with conditional rules applied. It shows cases where 'nameOfPet' is invalid because it's empty when 'hasPet' is true, and invalid because it's filled when 'hasPet' is false. ```typescript const invalidWithPet: FormModel = { name: 'Alex', age: 26, hasPet: true, nameOfPet: '', }; console.log(formValidator.validate(invalidWithPet)); // { nameOfPet: 'Value cannot be empty' } const invalidWithoutPet: FormModel = { name: 'Alex', age: 26, hasPet: false, nameOfPet: 'Doggy', }; console.log(formValidator.validate(invalidWithoutPet)); // { nameOfPet: 'Value must be null' } ``` -------------------------------- ### Implement .lessThanOrEqualTo Validation - TypeScript Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/lessThanOrEqualTo This example demonstrates how to use the `.lessThanOrEqualTo` rule from `fluentvalidation-ts` to validate that a number property does not exceed a specified maximum value. It includes setting up a validator class and testing it with valid and invalid inputs. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { passengers: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('passengers').lessThanOrEqualTo(4); } } const formValidator = new FormValidator(); formValidator.validate({ passengers: 4 }); // ✔ {} formValidator.validate({ passengers: 6 }); // ❌ { passengers: 'Value must be less than or equal to 4' } ``` -------------------------------- ### FluentValidation-TS: .null Rule (Default Usage) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/nullrule This example demonstrates the default behavior of the `.null` rule, where both `null` and `undefined` values are considered valid. ```APIDOC ## POST /validate/null/default ### Description Validates that a property is `null` or `undefined` by default. ### Method POST ### Endpoint /validate/null/default ### Parameters #### Request Body - **apiError** (string | null | undefined) - Required - The value to validate. ### Request Example ```json { "apiError": null } ``` ### Response #### Success Response (200) - **apiError** (string | null) - Returns an empty object if validation passes. #### Response Example ```json { "apiError": "Value must be null" } ``` ### Notes - The `includeUndefined` option defaults to `true`. - `null` and `undefined` values are considered valid. ``` -------------------------------- ### Using .maxLength Validator in fluentvalidation-ts Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/maxlength Demonstrates how to use the .maxLength validator to enforce a maximum length for a string property. It shows the import, validator class definition, and validation examples with both valid and invalid inputs. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { username: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('username').maxLength(20); } } const formValidator = new FormValidator(); formValidator.validate({ username: 'AlexPotter' }); // ✔ {} formValidator.validate({ username: 'ThisUsernameIsFarTooLong' }); // ❌ { username: 'Value must be no more than 20 characters long' } ``` -------------------------------- ### Username Availability Check with .mustAsync Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/mustasync This example demonstrates using the .mustAsync rule to validate a username against an API call that checks for availability. It imports AsyncValidator and defines a FormValidator class. ```typescript import { AsyncValidator } from 'fluentvalidation-ts'; type FormModel = { username: string; }; // Assuming 'api' is an object with an async method 'usernameIsAvailable' // const api = { usernameIsAvailable: async (username: string) => true }; class FormValidator extends AsyncValidator { constructor() { super(); this.ruleFor('username').mustAsync( async (username) => await api.usernameIsAvailable(username) ); } } const formValidator = new FormValidator(); // Example usage: // await formValidator.validateAsync({ username: 'ajp_dev123' }); // // ✔ {} // await formValidator.validateAsync({ username: 'ajp_dev' }); // // ❌ { username: 'Value is not valid' } ``` -------------------------------- ### Add Multiple Rules with .ruleFor - TypeScript Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ruleFor Illustrates chaining multiple validation rules to a property using `.ruleFor`. This example adds 'notEmpty' and 'maxLength' rules to the 'name' property. ```typescript // The result of adding a rule is again the rule chain builder, // so you can add multiple rules in a single call this.ruleFor('name').notEmpty().maxLength(100); ``` -------------------------------- ### FluentValidation-ts: .notUndefined Rule Example Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/notUndefined Demonstrates how to use the `.notUndefined()` rule in FluentValidation-ts to validate that a property is not undefined. This example shows validation scenarios with defined, null, missing, and undefined values. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { customerId?: number | null; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('customerId').notUndefined(); } } const formValidator = new FormValidator(); formValidator.validate({ customerId: 100 }); // ✔ {} formValidator.validate({ customerId: null }); // ✔ {} formValidator.validate({}); // ❌ { customerId: 'Value cannot be undefined' } formValidator.validate({ customerId: undefined }); // ❌ { customerId: 'Value cannot be undefined' } ``` -------------------------------- ### FluentValidation-TS: Using .undefined() Rule Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/undefinedRule Demonstrates how to apply the .undefined() rule to a property within a FluentValidation-TS validator class. It shows the setup with a TypeScript form model and validator, and provides examples of validating different inputs (empty object, undefined, number, null) and their expected results. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { customerId?: number | null; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('customerId').undefined(); } } const formValidator = new FormValidator(); formValidator.validate({}); // ✔ {} formValidator.validate({ customerId: undefined }); // ✔ {} formValidator.validate({ customerId: 100 }); // ❌ { customerId: 'Value must be undefined' } formValidator.validate({ customerId: null }); // ❌ { customerId: 'Value must be undefined' } ``` -------------------------------- ### FluentValidation-TS: .null Rule (Excluding undefined) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/nullrule This example shows how to configure the `.null` rule to strictly validate only `null` values by excluding `undefined`. ```APIDOC ## POST /validate/null/strict ### Description Validates that a property is strictly `null`, excluding `undefined` values. ### Method POST ### Endpoint /validate/null/strict ### Parameters #### Query Parameters - **includeUndefined** (boolean) - Optional - Set to `false` to exclude `undefined` values. #### Request Body - **apiError** (string | null | undefined) - Required - The value to validate. ### Request Example ```json { "apiError": undefined } ``` ### Response #### Success Response (200) - **apiError** (string | null) - Returns an empty object if validation passes. #### Response Example ```json { "apiError": "Value must be null" } ``` ### Notes - Set `includeUndefined: false` in the rule options to enable strict `null` validation. - Only `null` values are considered valid; `undefined` values will fail validation. ``` -------------------------------- ### Use .notEmpty() for String Validation in fluentvalidation-ts Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/notempty This example demonstrates how to use the `.notEmpty()` rule in fluentvalidation-ts to validate that a string property is not empty or whitespace. It shows how to define a validator, apply the rule, and then validate objects with both valid and invalid string values. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty(); } } const formValidator = new FormValidator(); formValidator.validate({ name: 'Alex' }); // ✔ {} formValidator.validate({ name: ' ' }); // ❌ { name: 'Value cannot be empty' } ``` -------------------------------- ### Validate number precision and scale with fluentvalidation-ts Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/precisionScale This example demonstrates how to use the `.precisionScale` rule to validate the precision and scale of a number property within a form model using fluentvalidation-ts. It shows successful and failing validation cases. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { price: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('price').precisionScale(4, 2); } } const formValidator = new FormValidator(); formValidator.validate({ price: 10.01 }); // ✔ {} formValidator.validate({ price: 0.001 }); // Too many digits after the decimal point // ❌ { price: 'Value must be no more than 4 digits in total, with allowance for 2 decimals' } formValidator.validate({ price: 100.1 }); // Too many digits (when accounting for reserved digits after the decimal point) // ❌ { price: 'Value must be no more than 4 digits in total, with allowance for 2 decimals' } ``` -------------------------------- ### Apply multiple .when() conditions in a chain (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/configuration/when Illustrates using multiple .when() conditions within a single rule chain in TypeScript. This example enforces specific delivery rates based on the delivery day. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { deliveryDay: string; deliveryRate: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('deliveryRate') .equal(4.99) .withMessage('Sunday rates must apply if delivery day is Sunday') .when((formModel) => formModel.deliveryDay === 'Sunday') .equal(2.99) .withMessage('Standard rates must apply if delivery day is Monday to Saturday') .when((formModel) => formModel.deliveryDay !== 'Sunday'); } } const formValidator = new FormValidator(); formValidator.validate({ deliveryDay: 'Sunday', deliveryRate: 4.99 }); // ✔ {} formValidator.validate({ deliveryDay: 'Sunday', deliveryRate: 2.99 }); // ❌ { deliveryRate: 'Sunday rates must apply if delivery day is Sunday' } formValidator.validate({ deliveryDay: 'Monday', deliveryRate: 2.99 }); // ✔ {} formValidator.validate({ deliveryDay: 'Monday', deliveryRate: 4.99 }); // ❌ { deliveryRate: 'Standard rates must apply if delivery day is Monday to Saturday' } ``` -------------------------------- ### Validate Model with FluentValidation-TS (Valid Case) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validationerrors This example shows how to use the validate method of a FluentValidation-TS validator with a model where all properties are valid. It illustrates the expected empty ValidationErrors object when no rules are violated. ```typescript formValidator.validate({ name: 'Alex', age: 26 }); // {} ``` -------------------------------- ### Validate Model with FluentValidation-TS (Valid Case) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validationErrors Shows an example of validating a model object where all properties satisfy the defined validation rules. The resulting ValidationErrors object is empty, indicating no errors. ```typescript formValidator.validate({ name: 'Alex', age: 26 }); // {} ``` -------------------------------- ### Apply .unless to all rules in the chain Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/configuration/unless Validates a delivery note's presence and length, skipping validation if the note is not required. This example demonstrates applying `.unless` to an entire rule chain. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { doesNotRequireDeliveryNote: boolean; deliveryNote: string | null; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('deliveryNote') .notNull() .notEmpty() .maxLength(1000) .unless((formModel) => formModel.doesNotRequireDeliveryNote); } } const formValidator = new FormValidator(); formValidator.validate({ doesNotRequireDeliveryNote: true, deliveryNote: null, }); // ✔ {} formValidator.validate({ doesNotRequireDeliveryNote: false, deliveryNote: null, }); // ❌ { deliveryNote: 'Value cannot be null' } ``` -------------------------------- ### Customize Error Messages and Conditions with .ruleFor - TypeScript Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ruleFor Shows how to customize error messages for validation rules and apply conditional logic using `.when` and `.unless`. This example targets the 'jobTitle' property. ```typescript this.ruleFor('name').notEmpty().maxLength(100); // You can specify a custom error message for each rule in the chain, // and provide a condition to determine when the rules should run this.ruleFor('jobTitle') .notEmpty() .withMessage('Please enter a Job Title') .maxLength(100) .withMessage('Please enter no more than 100 characters') .when((formModel) => formModel.isEmployed); // You can also provide a condition to determine when certain rules // should not run this.ruleFor('jobTitle') .equal('') .withMessage('You cannot enter a Job Title if you are not employed') .unless((formModel) => formModel.isEmployed); ``` -------------------------------- ### Implement .greaterThanOrEqualTo Rule in TypeScript Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/greaterThanOrEqualTo This example demonstrates how to use the .greaterThanOrEqualTo rule from fluentvalidation-ts to validate a number property. It checks if the 'age' property is at least 18. Requires 'fluentvalidation-ts'. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { age: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('age').greaterThanOrEqualTo(18); } } const formValidator = new FormFormValidator(); formValidator.validate({ age: 18 }); // ✔ {} formValidator.validate({ age: 16 }); // ❌ { age: 'Value must be greater than or equal to 18' } ``` -------------------------------- ### FluentValidation-TS: Validate Number is Inclusively Between Bounds Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/inclusiveBetween Demonstrates how to use the `.inclusiveBetween` rule to validate that a numeric property is greater than or equal to a lower bound and less than or equal to an upper bound. This example uses TypeScript and FluentValidation-TS. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { percentageComplete: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('percentageComplete').inclusiveBetween(0, 100); } } const formValidator = new FormValidator(); formValidator.validate({ percentageComplete: 50 }); // ✔ {} formValidator.validate({ percentageComplete: 110 }); // ❌ { percentageComplete: 'Value must be between 0 and 100 (inclusive)' } ``` -------------------------------- ### fluentvalidation-ts: .mustAsync with Async Predicate Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/mustAsync Demonstrates using the .mustAsync rule with an asynchronous predicate function that depends solely on the property's value. This example validates if a username is available via an API call. ```typescript import { AsyncValidator } from 'fluentvalidation-ts'; type FormModel = { username: string; }; class FormValidator extends AsyncValidator { constructor() { super(); this.ruleFor('username').mustAsync( async (username) => await api.usernameIsAvailable(username) ); } } const formValidator = new FormValidator(); await formValidator.validateAsync({ username: 'ajp_dev123' }); // ✔ {} await formValidator.validateAsync({ username: 'ajp_dev' }); // ❌ { username: 'Value is not valid' } ``` -------------------------------- ### FluentValidation-TS: Direct Rule on Object Property Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ValidationErrors This example illustrates what happens when a direct validation rule (other than `.setValidator`) is applied to an object property. If this rule fails before a `.setValidator` rule, the error in the main errors object will be a string. ```typescript import { Validator } from 'fluentvalidation-ts'; type ContactDetails = { name: string; emailAddress: string; }; class ContactDetailsValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty().withMessage('Please enter your name'); this.ruleFor('emailAddress') .emailAddress() .withMessage('Please enter a valid email address'); } } const contactDetailsValidator = new ContactDetailsValidator(); type FormModel = { contactDetails: ContactDetails | null }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('contactDetails') .notNull() // <--- If this rule fails we'll get a `string` error in the errors object .setValidator(() => contactDetailsValidator); } } const formValidator = new FormValidator(); formValidator.validate({ contactDetails: null }); // { contactDetails: 'Value cannot be null' } ``` -------------------------------- ### FluentValidation-ts: Validate Minimum String Length Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/minLength This code snippet demonstrates how to use the `.minLength` validator from the fluentvalidation-ts library. It defines a form model, a validator class extending `Validator`, and applies the `minLength` rule to the 'password' field, setting a minimum length of 6 characters. The examples show successful and failed validation scenarios. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { password: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('password').minLength(6); } } const formValidator = new FormValidator(); formValidator.validate({ password: 'supersecret' }); // ✔ {} formValidator.validate({ password: 'foo' }); // ❌ { password: 'Value must be at least 6 characters long' } ``` -------------------------------- ### FluentValidation-TS: Using .withMessage for Custom Error Messages Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/configuration/withmessage Demonstrates how to use the .withMessage method in FluentValidation-TS to provide custom error messages for validation rules. This example shows overriding default messages for 'notEmpty' and 'maxLength' rules. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('name') .notEmpty() .withMessage('Please enter your name') .maxLength(1000) .withMessage('Please enter no more than 1,000 characters'); } } const formValidator = new FormValidator(); formValidator.validate({ name: 'Alex' }); // ✔ {} formValidator.validate({ name: '' }); // ❌ { name: 'Please enter your name' } ``` -------------------------------- ### Nested Async Validator Example using .setAsyncValidator Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/setasyncvalidator Demonstrates how to use .setAsyncValidator to include a nested asynchronous validator that does not depend on the base model. This involves defining a separate validator for a nested object and returning an instance of it from a producer function. ```typescript import { AsyncValidator } from 'fluentvalidation-ts'; type ContactDetails = { name: string; emailAddress: string; }; class ContactDetailsValidator extends AsyncValidator { constructor() { super(); this.ruleFor('name').notEmpty(); this.ruleFor('emailAddress') .emailAddress() .mustAsync( async (emailAddress) => await api.emailAddressNotInUse(emailAddress) ) .withMessage('This email address is already in use'); } } const contactDetailsValidator = new ContactDetailsValidator(); type FormModel = { contactDetails: ContactDetails; }; class FormValidator extends AsyncValidator { constructor() { super(); this.ruleFor('contactDetails').setAsyncValidator( () => contactDetailsValidator ); } } const formValidator = new FormValidator(); await formValidator.validateAsync({ contactDetails: { name: 'Alex', emailAddress: 'alex123@example.com' }, }); // ✔ {} await formValidator.validateAsync({ contactDetails: { name: 'Alex', emailAddress: 'alex@example.com' }, }); // ❌ { contactDetails: { emailAddress: 'This email address is already in use' } } ``` -------------------------------- ### FluentValidation-ts: Use .ruleForTransformed to Validate Transformed String to Number Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/rulefortransformed This example demonstrates using .ruleForTransformed to convert a string property 'quantity' to a number and then applying numerical validation rules (not NaN, greater than 0, less than or equal to 100). It requires the fluentvalidation-ts library. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { quantity: string; }; class FormValidator extends Validator { constructor() { super(); this.ruleForTransformed('quantity', (q) => Number(q)) .must((numberQuantity) => !isNaN(numberQuantity)) .greaterThan(0) .lessThanOrEqualTo(100); } } ``` -------------------------------- ### FluentValidation-TS: Handling Validation Errors for Nested Objects Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ValidationErrors This example demonstrates the output of the `validate` method when using nested object validation. It shows an empty errors object for valid input and a structured errors object reflecting the nested validation failures. ```typescript formValidator.validate({ contactDetails: { name: 'Alex', emailAddress: 'alex@example.com' }, }); // {} ``` ```typescript formValidator.validate({ contactDetails: { name: '', emailAddress: 'alex@example.com' }, }); // { contactDetails: { name: 'Please enter your name' } } ``` -------------------------------- ### FluentValidation-TS: Validate array length and element range Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validationErrors This example shows how to combine array-level validation (checking if the array is empty) using `ruleFor` with element-level validation (checking if numbers are within a range) using `ruleForEach`. It demonstrates the validation of an empty array. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { scores: Array }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('scores') .must((scores) => scores.length > 0) .withMessage('Cannot be empty'); this.ruleForEach('scores').inclusiveBetween(1, 10); } } const formValidator = new FormValidator(); formValidator.validate({ scores: [] }); // { scores: 'Cannot be empty' } ``` -------------------------------- ### FluentValidation TS: Ensure number is greater than a threshold Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/greaterThan This example demonstrates how to use the .greaterThan() rule in fluentvalidation-ts to validate that a 'quantity' property is strictly greater than 0. It shows successful validation with a value of 2 and failed validation with a value of 0, including the expected error message. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { quantity: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('quantity').greaterThan(0); } } const formValidator = new FormValidator(); formValidator.validate({ quantity: 2 }); // ✔ {} formValidator.validate({ quantity: 0 }); // ❌ { quantity: 'Value must be greater than 0' } ``` -------------------------------- ### Validate Array Size and Individual Elements with FluentValidation-TS Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validationerrors This example shows how to combine validation for the array itself (e.g., checking if it's empty) using `ruleFor` and validation for individual elements using `ruleForEach`. If the array size validation fails, a string error is returned for the property. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { scores: Array }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('scores') .must((scores) => scores.length > 0) .withMessage('Cannot be empty'); this.ruleForEach('scores').inclusiveBetween(1, 10); } } const formValidator = new FormValidator(); // Example with an empty array formValidator.validate({ scores: [] }); // Expected output: { scores: 'Cannot be empty' } ``` -------------------------------- ### Instantiate and Use Validator (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Creates an instance of FormValidator and uses its `validate` method to check form model objects. Demonstrates validation of both valid and invalid data. ```typescript const formValidator = new FormValidator(); const valid: FormModel = { name: 'Alex', age: 26 }; console.log(formValidator.validate(valid)); // {} const invalid: FormModel = { name: '', age: 26 }; console.log(formValidator.validate(invalid)); // { name: 'Value cannot be empty' } ``` -------------------------------- ### Include fluentvalidation-ts via CDN (Latest Version) Source: https://fluentvalidation-ts.alexpotter.dev/docs/overview Includes the latest version of fluentvalidation-ts directly in an HTML file using a CDN link. This makes the Validator class accessible globally. ```html ``` -------------------------------- ### Include fluentvalidation-ts via CDN (Specific Version) Source: https://fluentvalidation-ts.alexpotter.dev/docs/overview Includes a specific version of fluentvalidation-ts via a CDN link in an HTML file. This is useful for maintaining compatibility with specific project requirements. ```html ``` -------------------------------- ### Add Custom Error Messages with .withMessage() Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Shows how to attach custom error messages to the .must() rules for more user-friendly feedback. ```typescript this.ruleFor('age') .notEmpty() .must((age) => !isNaN(Number(age))) .withMessage('Please enter a number') .must((age) => Number(age) >= 0) .withMessage('Please enter a non-negative number'); ``` -------------------------------- ### Basic FluentValidation-TS Usage Source: https://fluentvalidation-ts.alexpotter.dev/docs/overview Illustrates the core usage of fluentvalidation-ts. It shows how to define a validator class by extending `Validator`, add rules using `ruleFor`, and validate a model object. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; age: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty().withMessage('Please enter your name'); this.ruleFor('age') .greaterThanOrEqualTo(0) .withMessage('Please enter a non-negative number'); } } const formValidator = new FormValidator(); const valid: FormModel = { name: 'Alex', age: 26, }; formValidator.validate(valid); // {} const invalid: FormModel = { name: '', age: -1, }; formValidator.validate(invalid); // { name: 'Please enter your name', age: 'Please enter a non-negative number' } ``` -------------------------------- ### Validate Form Model with Nested Pet Object (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Demonstrates validating a form model containing a nested 'pet' object. Includes scenarios for a valid nested object and an invalid one (empty pet name), showing how errors are reported as nested objects. ```typescript const valid: FormModel = { name: 'Alex', age: 26, hasPet: true, pet: { name: 'Doggy', species: 'Dog' }, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(valid)); // {} const invalid: FormModel = { name: 'Alex', age: 26, hasPet: true, pet: { name: '', species: 'Cat' }, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(invalid)); // { pet: { name: 'Value cannot be empty' } } ``` -------------------------------- ### Validate Each Element in Array with .ruleForEach Source: https://fluentvalidation-ts.alexpotter.dev/docs/guides/arrayProperties Validates each element within an array property using chained rules. This example enforces that each score must be between 0 and 100 (inclusive). ```typescript this.ruleForEach('scores').greaterThanOrEqualTo(0).lessThanOrEqualTo(100); ``` -------------------------------- ### Validate Array Property with .ruleFor Source: https://fluentvalidation-ts.alexpotter.dev/docs/guides/arrayProperties Validates an array property by checking if any element fails a custom condition. This example ensures no score is less than 0 or greater than 100. ```typescript this.ruleFor('scores').must( (scores) => scores.filter((score) => score < 0 || score > 100).length === 0 ); ``` -------------------------------- ### Validate Hobbies Array Entries (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Demonstrates validating a form model with an array of hobbies. Shows successful validation with valid entries and error reporting for an empty string within the array. ```typescript const valid: FormModel = { name: 'Alex', age: 26, hasPet: false, nameOfPet: null, hobbies: ['Coding', 'Music', 'Eating'], }; console.log(formValidator.validate(valid)); // {} const invalid: FormModel = { name: 'Alex', age: 26, hasPet: false, nameOfPet: null, hobbies: ['Coding', '', 'Eating'], }; console.log(formValidator.validate(invalid)); // { hobbies: [null, 'Value cannot be empty', null] } ``` -------------------------------- ### Instantiate and Use Validator with Different Ambient Contexts (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/guides/ambientContext Shows how to create instances of the FormValidator with different 'country' contexts ('UK' and 'US'). It then validates sample 'pubGoer' objects against these context-specific validators, illustrating the impact of ambient context on validation results. ```typescript const ukValidator = new FormValidator('UK'); const usValidator = new FormValidator('US'); const pubGoer = { age: 20 }; const ukResult = ukValidator.validate(pubGoer); // {} const usResult = usValidator.validate(pubGoer); // { age: 'Value must be greater than or equal to 21' } ``` -------------------------------- ### Create Reusable Validation Functions Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Extracts validation logic into reusable functions (beNumeric, beNonNegative) to avoid repetition across multiple validators. ```typescript const beNumeric = (value: string) => !isNaN(Number(value)); const beNonNegative = (value: string) => Number(value) >= 0; ``` -------------------------------- ### Apply .unless to a specific rule in the chain Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/configuration/unless Validates that age is entered and is at least 18, but only if an alcoholic drink has been chosen. This example targets `.unless` to a specific rule using the 'AppliesToCurrentValidator' option. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { age: number | null; alcoholicDrink: string | null; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('age') .notNull() .greaterThanOrEqualTo(18) .unless((formModel) => formModel.alcoholicDrink == null, 'AppliesToCurrentValidator'); } } const formValidator = new FormValidator(); formValidator.validate({ age: 17, alcoholicDrink: null, }); // ✔ {} formValidator.validate({ age: 17, alcoholicDrink: 'Beer', }); // ❌ { age: 'Value must be greater than or equal to 18' } formValidator.validate({ age: null, alcoholicDrink: null, }); // ❌ { age: 'Value cannot be null' } ``` -------------------------------- ### Perform Async Validation Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/asyncvalidator Shows how to instantiate an AsyncValidator and use the `.validateAsync` method to validate a model instance, awaiting the Promise result. ```typescript const formValidator = new FormValidator(); const validResult = await formValidator.validateAsync({ username: 'ajp_dev123', }); // ✔ {} const invalidResult = await formValidator.validateAsync({ username: 'ajp_dev', }); // ❌ { username: 'This username is already taken' } ``` -------------------------------- ### Implement Conditional Validation Rules (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Adds conditional validation rules to 'nameOfPet' using `.when()` and `.unless()`. The 'nameOfPet' field must be present if 'hasPet' is true, and must be null if 'hasPet' is false. ```typescript this.ruleFor('nameOfPet') .notNull() .notEmpty() .when((formModel) => formModel.hasPet); this.ruleFor('nameOfPet') .null() .unless((formModel) => formModel.hasPet); ``` -------------------------------- ### FluentValidation.ts: .setValidator (Recursive Validation) Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/setValidator Illustrates validating recursive (self-referencing) models using `.setValidator`. The example shows an `Employee` model where a `lineManager` is also an `Employee`, requiring a recursive validator definition. ```typescript import { Validator } from 'fluentvalidation-ts'; type Employee = { name: string; lineManager: Employee | null; }; class EmployeeValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty(); this.ruleFor('lineManager').setValidator(() => new EmployeeValidator()); } } const validator = new EmployeeValidator(); validator.validate({ name: 'Bob', lineManager: { name: 'Alice', lineManager: null, }, }); // ✔ {} validator.validate({ name: 'Alex', lineManager: { name: '', lineManager: null, }, }); // ❌ { lineManager: { name: 'Value cannot be empty' } } ``` -------------------------------- ### Validate a Model Instance Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validator Shows how to use the `.validate` method of a validator instance to check a model object. It illustrates expected outputs for both valid and invalid inputs. ```typescript const formValidator = new FormValidator(); const validResult = formValidator.validate({ name: 'Alex' }); // ✔ {} const invalidResult = formValidator.validate({ name: '' }); // ❌ { name: 'Please enter your name' } ``` -------------------------------- ### Import AsyncValidator Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/asyncvalidator Imports the AsyncValidator class from the fluentvalidation-ts library. ```typescript import { AsyncValidator } from 'fluentvalidation-ts'; ``` -------------------------------- ### Using Context-Aware Validators (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/guides/ambientcontext Shows how to instantiate and use validators that depend on ambient context. Different validator instances are created with specific context (e.g., 'UK', 'US') to perform validation on a given data model. ```typescript const ukValidator = new FormValidator('UK'); const usValidator = new FormValidator('US'); const pubGoer = { age: 20 }; const ukResult = ukValidator.validate(pubGoer); // {} const usResult = usValidator.validate(pubGoer); // { age: 'Value must be greater than or equal to 21' } ``` -------------------------------- ### Import Validator Class (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Imports the Validator class from the fluentvalidation-ts library, which is the base class for creating custom validators. ```typescript import { Validator } from 'fluentvalidation-ts'; ``` -------------------------------- ### Define Form Model (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Defines a TypeScript type for a simple form model with 'name' (string) and 'age' (number) properties. ```typescript type FormModel = { name: string; age: number; }; ``` -------------------------------- ### FluentValidation-TS: Using .notEqual Rule Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/rules/notequal Demonstrates how to use the .notEqual rule to validate that a boolean property is not equal to false. This rule uses strict inequality. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { acceptsTermsAndConditions: boolean; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('acceptsTermsAndConditions').notEqual(false); } } const formValidator = new FormValidator(); formValidator.validate({ acceptsTermsAndConditions: true }); // ✔ {} formValidator.validate({ acceptsTermsAndConditions: false }); // ❌ { acceptsTermsAndConditions: `Value must not equal 'false'` } ``` -------------------------------- ### Update Form Model for Conditional Rules (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Extends the FormModel to include 'hasPet' (boolean) and 'nameOfPet' (string or null) properties, preparing for conditional validation logic. ```typescript type FormModel = { name: string; age: number; hasPet: boolean; nameOfPet: string | null; }; ``` -------------------------------- ### Define Validator with .ruleFor - TypeScript Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ruleFor Demonstrates how to initialize a validator for a model using `.ruleFor` to target specific properties. It shows the basic structure for defining rules on a 'name' property. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; isEmployed: boolean; jobTitle: string | null; }; class FormValidator extends Validator { constructor() { super(); // Returns a rule chain builder for the 'name' property this.ruleFor('name'); } } ``` -------------------------------- ### FluentValidation-TS: Validate Nested Object Properties Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/ValidationErrors This example shows how to define a validator for a nested ContactDetails object and then use `.setValidator` in a parent FormValidator to apply these rules. It demonstrates how validation errors are structured based on the nested object. ```typescript import { Validator } from 'fluentvalidation-ts'; type ContactDetails = { name: string; emailAddress: string; }; class ContactDetailsValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty().withMessage('Please enter your name'); this.ruleFor('emailAddress') .emailAddress() .withMessage('Please enter a valid email address'); } } const contactDetailsValidator = new ContactDetailsValidator(); type FormModel = { contactDetails: ContactDetails }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('contactDetails').setValidator(() => contactDetailsValidator); } } const formValidator = new FormValidator(); ``` -------------------------------- ### Implement Custom Validation Logic with .must() Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Demonstrates using the .must() rule to define custom validation logic for the 'age' field, ensuring it's numeric and non-negative. ```typescript this.ruleFor('age') .notEmpty() .must((age) => !isNaN(Number(age))) .must((age) => Number(age) >= 0); ``` -------------------------------- ### Import Validator from fluentvalidation-ts Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validator Imports the core Validator class from the fluentvalidation-ts library. This is the foundational step for creating any validator. ```typescript import { Validator } from 'fluentvalidation-ts'; ``` -------------------------------- ### Create Basic Form Validator (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Defines a custom validator class 'FormValidator' that extends the base Validator class and is typed with the 'FormModel'. ```typescript class FormValidator extends Validator {} ``` -------------------------------- ### Apply Reusable Rules with Embedded Messages Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Utilizes the combined predicate and message objects directly in the validator rule chain, simplifying the syntax. ```typescript this.ruleFor('age') .notEmpty() .must(beNumeric) .must(beNonNegative); ``` -------------------------------- ### Validate Each Item in Hobbies Array (TypeScript) Source: https://fluentvalidation-ts.alexpotter.dev/docs/tutorial Applies validation rules to each element within the 'hobbies' array using FluentValidation-TS. It ensures no hobby is empty and has a maximum length of 100 characters. ```typescript this.ruleForEach('hobbies').notEmpty().maxLength(100); ``` -------------------------------- ### Define FluentValidation-TS Validator and Rules Source: https://fluentvalidation-ts.alexpotter.dev/docs/api/core/validationerrors This snippet demonstrates how to define a validator class using FluentValidation-TS, including setting up rules for model properties like 'name' and 'age'. It shows how to instantiate the validator and apply validation rules. ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { name: string; age: number; }; class FormValidator extends Validator { constructor() { super(); this.ruleFor('name').notEmpty().withMessage('Please enter your name'); this.ruleFor('age') .greaterThanOrEqualTo(0) .withMessage('Your age must be a positive number'); } } const formValidator = new FormValidator(); ```