### Install context package Source: https://github.com/ealush/vest/blob/latest/packages/context/README.md Installs the 'context' package using npm. This is the first step to use the library in your project. ```bash npm i context ``` -------------------------------- ### String Does Not Start With Assertion (Throws) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a string does not begin with a specified prefix. This example demonstrates assertions that are expected to throw errors. ```javascript enforce('aba').doesNotStartWith('ab'); enforce('some_string').doesNotStartWith('some_'); enforce('string with spaces').doesNotStartWith('string with s'); enforce('aaaa ').doesNotStartWith('aaaa '); // throws ``` -------------------------------- ### Install Vast using npm Source: https://github.com/ealush/vest/blob/latest/packages/vast/README.md This command installs the Vast library using npm. It is a prerequisite for using Vast in your project. ```bash npm i vast ``` -------------------------------- ### String Starts With Assertion (Throws) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a string begins with a specified prefix. This example demonstrates assertions that are expected to throw errors. ```javascript enforce('for').startsWith('tor'); enforce('aaaab').startsWith('aab'); enforce('aa').startsWith('aaa'); enforce(42).startsWith('b'); enforce(42).startsWith(50); enforce(true).startsWith(100); // throws ``` -------------------------------- ### Install Anyone Utility Library Source: https://github.com/ealush/vest/blob/latest/packages/anyone/README.md Instructions for installing the 'anyone' package using npm or yarn package managers. This is the first step to using the library's boolean checking utilities. ```bash npm i anyone # or yarn add anyone ``` -------------------------------- ### Usage Examples for Anyone Boolean Helpers (JavaScript) Source: https://github.com/ealush/vest/blob/latest/packages/anyone/README.md Demonstrates how to import and use the 'any', 'one', 'all', and 'none' helper functions from the 'anyone' library. Shows examples with various truthy and falsy values, including function callbacks. ```javascript import { any, one, all, none } from 'anyone'; const maybeTrue = () => true; const alwaysFalse = () => false; any(alwaysFalse, 0, 'value'); // → true ("value" is truthy) all(1, maybeTrue, 'ok'); // → true one(alwaysFalse, null, 5); // → true (only the number is truthy) none(alwaysFalse, 0, '', () => false); // → true (no truthy values found) ``` -------------------------------- ### String Starts With Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a string begins with a specified prefix. This example demonstrates successful assertions. ```javascript enforce('aba').startsWith('ab'); enforce('some_string').startsWith('some_'); enforce('string with spaces').startsWith('string with s'); enforce('aaaa ').startsWith('aaaa '); // passes ``` -------------------------------- ### Start Local Development Server with Yarn Source: https://github.com/ealush/vest/blob/latest/website/README.md Starts a local development server for the Docusaurus 2 website. This command enables live reloading for most changes, allowing for rapid development. ```shell $ yarn start ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/ealush/vest/blob/latest/website/README.md Installs all necessary project dependencies using the Yarn package manager. This is typically the first step before running other commands. ```shell $ yarn ``` -------------------------------- ### Install Vest using npm Source: https://github.com/ealush/vest/blob/latest/README.md This command installs the Vest validation framework using npm, the default package manager for Node.js. Ensure you have Node.js and npm installed on your system. ```shell npm i vest ``` -------------------------------- ### Vest: Full Example with Named Groups and Conditional Skipping Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_tests/advanced_test_features/grouping_tests.md A comprehensive example showcasing Vest's `group()`, `test()`, `enforce()`, and `skip()` functionalities. It demonstrates how to define tests, group them into 'signIn' and 'signUp' sections, and conditionally skip entire groups based on data properties. ```javascript import { create, test, group, enforce, skip } from 'vest'; create(data => { test('userName', "Can't be empty", () => { enforce(data.username).isNotEmpty(); }); test('password', "Can't be empty", () => { enforce(data.password).isNotEmpty(); }); group('signIn', () => { skip(!data.userExists); // Skips the signin group if userExists is false test( 'userName', 'User not found. Please check if you typed it correctly.', findUserName(data.username), ); }); group('signUp', () => { skip(!!data.userExists); // Skips the signup group if userExists is true test('email', 'Email already registered', isEmailRegistered(data.email)); test('age', 'You must be at least 18 years old to join', () => { enforce(data.age).largerThanOrEquals(18); }); }); }); ``` -------------------------------- ### Install validator.js package Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/consuming_external_rules.md Installs the validator.js package using npm, which provides a wide range of additional validation functions. ```bash npm i validator ``` -------------------------------- ### String Does Not Start With Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a string does not begin with a specified prefix. This example demonstrates successful assertions. ```javascript enforce('for').doesNotStartWith('tor'); enforce('aaaab').doesNotStartWith('aab'); enforce('aa').doesNotStartWith('aaa'); enforce(42).doesNotStartWith('b'); enforce(42).doesNotStartWith(50); enforce(true).doesNotStartWith(100); // passes ``` -------------------------------- ### Install Vest using npm Source: https://github.com/ealush/vest/blob/latest/packages/vest/README.md Provides the command to install the Vest validation framework using npm. This is the standard method for adding Vest to a Node.js project. ```shell npm i vest ``` -------------------------------- ### String Parsing Examples: trim, toUpper, toTitle Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/data_parsers.md Provides examples of common string parsing functions available on `enforce.isString()` chains. These include `trim` for removing whitespace, `toUpper` for converting to uppercase, and `toTitle` for capitalizing the first letter of each word. The `.parse()` method is used to directly obtain the transformed string. ```javascript enforce.isString().trim().parse(' vest '); // → 'vest' enforce.isString().toUpper().parse('vest'); // → 'VEST' enforce.isString().toTitle().parse('hello world'); // → 'Hello World' ``` -------------------------------- ### startsWith Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Determines whether a string starts with the characters of a specified string. It passes if the enforced value is a string and starts with the provided prefix, and throws otherwise. ```APIDOC ## startsWith ### Description Determines whether a string starts with the characters of a specified string. ### Method `enforce(value).startsWith(prefix)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript enforce('aba').startsWith('ab'); enforce('some_string').startsWith('some'); ``` ### Response #### Success Response (200) Passes if the enforced value is a string and starts with the specified prefix. #### Response Example None (This is a boolean check, not a data retrieval operation) ### Error Handling Throws an error if the enforced value is not a string or does not start with the specified prefix. ``` -------------------------------- ### Install n4s Assertion Library Source: https://github.com/ealush/vest/blob/latest/packages/n4s/README.md Installs the 'n4s' package, Vest's standalone assertion library, using npm. ```bash npm i n4s ``` -------------------------------- ### Install Vest 6 Source: https://github.com/ealush/vest/blob/latest/website/src/pages/vest-6-is-ready.md Installs the latest stable version of Vest using npm. This is the first step to using Vest 6 in your project. ```bash npm install vest ``` -------------------------------- ### Example: Password Confirmation Validation Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Sets up validation for 'password' and 'confirm' fields. It includes 'confirm' validation when the current field is 'password', ensuring passwords match if 'password' is being validated. ```javascript create((data = {}, currentField) => { only(currentField); include('confirm').when('password'); test('password', 'password is required', () => { enforce(data.password).isNotBlank(); }); test('confirm', 'Passwords do not match', () => { enforce(data.confirm).equals(data.password); }); }); ``` -------------------------------- ### Vest Stateful Validation Flow Example Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Illustrates the step-by-step process of Vest's stateful validation, showing how results are merged and maintained across validation runs, even when only specific fields are validated. ```text Step 1: User fills "Password" field └─→ suite.run() validates password └─→ Result: { password: ✓ } Step 2: User fills "Username" field └─→ suite.only('username').run() └─→ Vest runs ONLY username tests └─→ Vest MERGES with previous password result └─→ Result: { username: ?, password: ✓ } ← Full picture! Step 3: User fixes username error └─→ suite.only('username').run() └─→ Result: { username: ✓, password: ✓ } ← Ready to submit! ``` -------------------------------- ### Vest: Example of linked password and confirm fields validation Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_your_suite/including_and_excluding/include.md This Vest usage example demonstrates linking 'password' and 'confirm' fields. It uses `only(currentField)` to focus on the active field and `include('confirm').when('password')` to ensure 'confirm' is validated when 'password' is the `currentField`. It includes basic tests for password requirement and matching. ```javascript create((data = {}, currentField) => { only(currentField); include('confirm').when('password'); test('password', 'password is required', () => { enforce(data.password).isNotBlank(); }); test('confirm', 'Passwords do not match', () => { enforce(data.confirm).equals(data.password); }); }); ``` -------------------------------- ### Install and Import External Rules for Vest (JavaScript) Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Explains how to install and import external validation rules, specifically from the `validator.js` library, for use with Vest. It emphasizes importing individual rules to minimize bundle size. This is a prerequisite for extending Vest with custom or third-party logic. ```bash npm i validator ``` ```javascript import isCurrency from 'validator/es/lib/isCurrency'; import isMobilePhone from 'validator/es/lib/isMobilePhone'; ``` -------------------------------- ### Replace promisify and staticSuite with new Suite Object API (Vest) Source: https://github.com/ealush/vest/blob/latest/website/docs/upgrade_guide.md The `promisify` and `staticSuite` utilities have been removed in V6. Use `await suite.run()` instead of `promisify`, and `suite.runStatic()` instead of `staticSuite`. ```javascript ```diff - import { staticSuite } from 'vest'; - const suite = staticSuite(() => { ... }); - suite(data); + import { create } from 'vest'; + const suite = create(() => { ... }); + suite.runStatic(data); ``` ``` -------------------------------- ### Complete Form Validation Implementation Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt A full React component example integrating suite.only() for blur events, isTested() for error visibility, and standard suite.run() for form submission. ```javascript import suite from './validation'; function Form() { const [formData, setFormData] = useState({}); const [result, setResult] = useState(suite.get()); const handleChange = e => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); }; const handleBlur = e => { const { name } = e.target; // Validate only the blurred field const res = suite.only(name).run(formData); setResult(res); }; const handleSubmit = e => { e.preventDefault(); // Validate all fields on submit const res = suite.run(formData); setResult(res); if (res.isValid()) { // Submit the form } }; // Only show error if field was tested const showError = fieldName => { return result.isTested(fieldName) && result.hasErrors(fieldName); }; return (
{showError('username') && {result.getError('username')}}
); } ``` -------------------------------- ### Configure isURL Rule with Options Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/isUrl.md Shows an example of using the isURL rule with a detailed options object to customize validation criteria such as protocols, TLD requirements, and protocol presence. ```javascript enforce(url).isURL({ protocols: ['http', 'https', 'ftp'], require_tld: true, require_protocol: false, require_host: true, require_port: false, require_valid_protocol: true, allow_underscores: false, allow_trailing_dot: false, allow_protocol_relative_urls: false, allow_fragments: true, allow_query_components: true, validate_length: true, }); ``` -------------------------------- ### Data Parsing and Transformation Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Shows how to use lazy chains with parsers to transform data. Includes examples of running parsers on individual values and within schema definitions. ```javascript const result = enforce.isString().trim().toUpper().run(' hello '); const value = enforce.isString().trim().toUpper().parse(' hello '); const schema = enforce.shape({ name: enforce.isString().trim().toTitle(), age: enforce.isNumeric().toNumber().clamp(0, 120) }); schema.parse({ name: ' jANE DOE ', age: '180' }); ``` -------------------------------- ### Resetting All Validation State with suite.reset() Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Provides a simple example of how to use the `suite.reset()` method to clear all validation state, typically used for form resets or when starting new transactions. ```javascript suite.reset(); ``` -------------------------------- ### Vest 4 to Vest 5: Removing skipWhen Source: https://github.com/ealush/vest/blob/latest/website/docs/upgrade_guide.md Illustrates the removal of `skipWhen` in Vest 5, as eager execution mode is now the default. The example shows how to refactor code where `skipWhen` was used to prevent validation of fields with existing errors. ```diff - import {create, test, skipWhen} from 'vest'; + import {create, test} from 'vest'; const suite = create(() => { - skipWhen(res => res.hasErrors('username'), () => { test('username', 'username already taken', () => { // ... }); - }); }); ``` -------------------------------- ### Vest 4 to Vest 5: Removed skip.group and only.group Source: https://github.com/ealush/vest/blob/latest/website/docs/upgrade_guide.md Demonstrates the refactoring required due to the removal of `skip.group` and `only.group` in Vest 5. The examples show how to apply `skip` and `only` directly within group definitions or use `skip(true)` for group-level skipping. ```diff const suite = create(() => { - skip.group('group1', 'username'); group('group1', () => { + skip('username'); test('username', 'message', () => { // ... }); }); }); ``` ```diff const suite = create(() => { - skip.group('group1'); group('group1', () => { + skip(true); test('field1', 'message', () => { // ... }); }); }); ``` -------------------------------- ### Basic Suite with Result Helpers in JavaScript Source: https://github.com/ealush/vest/blob/latest/packages/vest/README.md Illustrates a basic signup validation suite using Vest. It includes tests for email (required and format) and password (minimum length). The example shows how to run the suite and use result helpers like `hasErrors` and `getErrors` to check and retrieve validation outcomes. ```javascript import { create, test, enforce } from 'vest'; const signupSuite = create(data => { test('email', 'Email is required', () => { enforce(data.email).isNotBlank().isEmail(); }); test('password', 'Password must be at least 8 characters', () => { enforce(data.password).isString().longerThanOrEquals(8); }); }); const result = await signupSuite.run({ email: '', password: 'short' }); result.hasErrors('email'); // true result.getErrors('password'); // ['Password must be at least 8 characters'] ``` -------------------------------- ### Check if a string starts with a specified substring Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Determines whether a string starts with the characters of a specified string. This is useful for validating prefixes or specific beginnings of text. It passes if the string starts with the substring and throws otherwise. ```javascript enforce('some_string').startsWith('some'); // passes ``` ```javascript enforce('some_string').startsWith('string'); // throws ``` -------------------------------- ### Create and use state with Vast (JavaScript) Source: https://github.com/ealush/vest/blob/latest/packages/vast/README.md Demonstrates creating a state container with an optional global change listener, registering a state key with an initial value, and using its getter and setter. The setter can accept a new value or an updater function. ```javascript import { createState } from 'vast'; // Optional callback runs on every state change const state = createState(() => console.log('state changed')); // Create a key with an initial value const useColor = state.registerStateKey('blue'); const [color, setColor] = useColor(); setColor('red'); // Next call returns the updated value const [current] = useColor(); // current === 'red' ``` ```javascript const [count, setCount] = state.registerStateKey(0)(); setCount(prev => prev + 1); ``` -------------------------------- ### Extending Vest with Reusable Custom Rules Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/creating_custom_rules.md Illustrates how to add reusable custom validation rules to Vest using `enforce.extend`. This example adds rules for checking valid email format, object key existence, and password matching. ```javascript enforce.extend({ isValidEmail: value => value.indexOf('@') > -1, hasKey: (value, key) => value.hasOwnProperty(key), passwordsMatch: (passConfirm, options) => passConfirm === options.passConfirm && options.passIsValid, }); enforce(user.email).isValidEmail(); ``` -------------------------------- ### Quick Start: Basic Form Validation with VestJS Source: https://github.com/ealush/vest/blob/latest/website/static/llms-consumer.txt Demonstrates a basic form validation suite using VestJS. It includes required and format checks for username and email fields. The suite can be run and its results queried for validity and errors. ```javascript import { create, test, enforce } from 'vest'; const suite = create((data = {}) => { test('username', 'Username is required', () => { enforce(data.username).isNotBlank(); }); test('username', 'Username must be at least 3 characters', () => { enforce(data.username).longerThanOrEquals(3); }); test('email', 'Email is not valid', () => { enforce(data.email).isNotBlank().isEmail(); }); }); // Run the suite const result = suite(formData); result.isValid(); // true if the entire suite passed result.isValid('username'); // true if the 'username' field passed result.hasErrors('email'); // true if 'email' has errors result.getErrors('email'); // ['Email is not valid'] ``` -------------------------------- ### Deploy Website to GitHub Pages with Yarn Source: https://github.com/ealush/vest/blob/latest/website/README.md Builds the website and deploys it to the `gh-pages` branch, specifically for hosting on GitHub Pages. Requires setting the GitHub username and optionally using SSH. ```shell $ GIT_USER= USE_SSH=true yarn deploy ``` -------------------------------- ### String Parsing Examples: Splitting and Whitespace Normalization Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/data_parsers.md Demonstrates string parsing functions related to splitting and handling whitespace. `split` divides a string into an array based on a separator, with an optional limit. `normalizeWhitespace` collapses multiple spaces and trims, while `stripWhitespace` removes all whitespace characters. ```javascript enforce.isString().split(',', 2).parse('a,b,c'); // → ['a', 'b'] enforce.isString().normalizeWhitespace().parse(' v e s t '); // → 'v e s t' enforce.isString().stripWhitespace().parse(' v e s t '); // → 'vest' ``` -------------------------------- ### Create a VestJS Validation Suite Source: https://github.com/ealush/vest/blob/latest/website/static/llms-consumer.txt Shows how to create a validation suite using VestJS's `create` function. This function initializes a validation context that can retain state across multiple runs. It also demonstrates how to run the suite and access its current state. ```javascript import { create } from 'vest'; const suite = create((data, currentField) => { // validations go here }); // Run the suite const result = suite(formData, 'username'); // Access current state at any time (even outside the suite) const currentState = suite.get(); ``` -------------------------------- ### skipWhen Immediate Skip Example (JavaScript) Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Demonstrates how skipWhen immediately skips the provided callback if the condition is truthy. In this example, the condition is `true`, so the console log inside the callback will not be executed, highlighting the skipping behavior. ```javascript skipWhen(true, () => { console.log('This will NOT run because the condition is true'); }); ``` -------------------------------- ### Vest isISO8601 Rule Example Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/date.md Demonstrates the isISO8601 rule for validating strings against the ISO 8601 date format. It includes examples of basic usage and applying options like strict and strictSeparator for enhanced validation. ```javascript import { enforce } from 'vest'; import 'vest/date'; const dateString = '2020-07-10T15:00:00.000'; // Basic usage enforce(dateString).isISO8601(); // Usage with options enforce(dateString).isISO8601({ strict: true, strictSeparator: true, }); ``` -------------------------------- ### Handling Suite Completion with .afterEach() Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_your_suite/accessing_the_result.md Demonstrates how to register callbacks that execute after each test cycle in a suite. It highlights the recommended approach of placing conditional logic inside the callback rather than chaining conditionally. ```javascript import { create, test, enforce } from 'vest'; const suite = create(data => { test('UserEmail', 'Marked as spam address', async () => await isKnownSpammer(data.address)); test('UserName', 'must not be blacklisted', async () => await isBlacklistedUser(data.username)); }); suite .afterEach(() => { const res = suite.get(); if (res.hasErrors('UserName')) { showUserNameErrors(res.errors); } reportToServer(res); promptUserQuestionnaire(res); }) .run(); ``` ```javascript // Recommended: Perform conditional checks within the after callback suite .afterEach(() => { if (field === 'username') { /*do something*/ } }) .run(); ``` -------------------------------- ### Vest.js Form Field Validation on Blur Example Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Provides a real-world example of using Vest.js for form field validation triggered on blur events. It utilizes the `only` modifier to validate just the field that lost focus and `afterEach` to update the UI with validation results. ```javascript // In your form component function handleBlur(fieldName, formData) { suite .only(fieldName) .afterEach(() => setValidationResult(suite.get())) .run(formData); } // Usage in React // handleBlur('email', formData)} // onChange={handleChange} // />; ``` -------------------------------- ### Build Static Website Content with Yarn Source: https://github.com/ealush/vest/blob/latest/website/README.md Generates the static content for the website into the `build` directory. The output can be hosted on any static content hosting service. ```shell $ yarn build ``` -------------------------------- ### Reset state with Vast (JavaScript) Source: https://github.com/ealush/vest/blob/latest/packages/vast/README.md Illustrates how to reset all registered state keys back to their initial values using the `state.reset()` method. Setters remain functional after a reset. ```javascript state.reset(); const [color, setColor] = useColor(); setColor('purple'); ``` -------------------------------- ### Handle Suite Completion with Promises Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Demonstrates the recommended approach of using await with suite.run() to handle validation results once all synchronous and asynchronous tests have finished. ```javascript const result = await suite.run(formData); if (result.isValid()) { // All tests passed! Submit the form. submitForm(formData); } else { // Handle errors showErrors(result.getErrors()); } ``` -------------------------------- ### Complete Form Validation Example with Vest Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_your_suite/dirty_checking.md This comprehensive example illustrates a React form component utilizing Vest for validation. It integrates handleChange, handleBlur (using suite.only()), and handleSubmit functions, along with conditional error rendering based on isTested(). This showcases a practical implementation of Vest's interaction handling features. ```javascript import suite from './validation'; function Form() { const [formData, setFormData] = useState({}); const [result, setResult] = useState(suite.get()); const handleChange = e => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); }; const handleBlur = e => { const { name } = e.target; // Validate only the blurred field const res = suite.only(name).run(formData); setResult(res); }; const handleSubmit = e => { e.preventDefault(); // Validate all fields on submit const res = suite.run(formData); setResult(res); if (res.isValid()) { // Submit the form } }; // Only show error if field was tested const showError = fieldName => { return result.isTested(fieldName) && result.hasErrors(fieldName); }; return (
{showError('username') && {result.getError('username')}}
); } ``` -------------------------------- ### Subscribe to state changes with Vast (JavaScript) Source: https://github.com/ealush/vest/blob/latest/packages/vast/README.md Shows how to register a state key with a per-key `onUpdate` callback. This callback receives the previous and current values and fires before the global `onStateChange`. ```javascript const logColorChange = (next, prev) => console.log(`color: ${prev} -> ${next}`); const useColor = state.registerStateKey('blue', logColorChange); useColor()[1]('green'); // logs: color: blue -> green ``` -------------------------------- ### Extending Vest Enforce with Custom Rules and TypeScript Support Source: https://github.com/ealush/vest/blob/latest/website/docs/typescript_support.md Shows how to extend Vest's 'enforce' object with custom validation rules, providing value-first signatures for better TypeScript integration. The example defines 'isValidEmail' and 'isWithinRange' and demonstrates how to declare their types within the 'n4s.EnforceMatchers' global interface for compile-time checking. It concludes with examples of using these custom rules. ```typescript import { enforce } from 'vest'; const customRules = { isValidEmail: (value: string) => value.includes('@'), isWithinRange: (value: number, min: number, max: number) => value >= min && value <= max, }; enforce.extend(customRules); declare global { namespace n4s { interface EnforceMatchers { isValidEmail: (value: string) => boolean; isWithinRange: (value: number, min: number, max: number) => boolean; } } } enforce('test@example.com').isValidEmail(); enforce(10).isWithinRange(5, 15); ``` -------------------------------- ### Is Not Value Of Object Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value does not exist as a property value within an object. This example demonstrates a successful assertion. ```javascript enforce('Delta').isNotValueOf({ a: 'Alpha', b: 'Bravo', c: 'Charlie' }); // passes ``` -------------------------------- ### Is Value Of Object Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value exists as a property value within an object. This example demonstrates a successful assertion. ```javascript enforce('Bravo').isValueOf({ a: 'Alpha', b: 'Bravo', c: 'Charlie' }); // passes ``` -------------------------------- ### Create a Basic Validation Suite in JavaScript Source: https://github.com/ealush/vest/blob/latest/packages/vest/README.md Demonstrates how to create a validation suite using Vest. It defines tests for username validation, including checking for presence, minimum length, and uniqueness using asynchronous validation. The suite is then run with provided data. ```javascript import { create, test, enforce } from 'vest'; const suite = create(data => { test('username', 'Username is required', () => { enforce(data.username).isNotBlank(); }); test('username', 'Username must be at least 3 chars', () => { enforce(data.username).longerThanOrEquals(3); }); test('username', 'Username already taken', async () => { await doesUserExist(data.username); }); }); const result = await suite.run(formData); ``` -------------------------------- ### Vest: Async rejection with custom message Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_tests/failing_with_a_custom_message.md Provides examples of how asynchronous Vest tests can reject their promises with a custom string message. ```javascript test('price', () => { return apiCall().then(() => { throw 'Price must be positive'; }); }); test('price', () => { return Promise.reject('Price must be positive'); }); ``` -------------------------------- ### Create and use isolated context with createContext Source: https://github.com/ealush/vest/blob/latest/packages/context/README.md Demonstrates creating an isolated context using `createContext` and running code within that context. The `logRequest` function shows how to access the current context value using `use()`. ```javascript import { createContext } from 'context'; const requestContext = createContext({ requestId: undefined }); function handleRequest(requestId) { return requestContext.run({ requestId }, () => { logRequest(); return doWork(); }); } function logRequest() { // Inside run → current context value console.log(requestContext.use().requestId); } ``` -------------------------------- ### Is Not Key Of Object Assertion (Throws) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value does not exist as a key within an object. This example demonstrates assertions that are expected to throw errors. ```javascript enforce('bananas').isNotKeyOf({ bananas: 5 }); enforce(1976).isNotKeyOf({ 1976: 'Rocky' }); // throws ``` -------------------------------- ### Is Not Value Of Object Assertion (Throws) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value does not exist as a property value within an object. This example demonstrates an assertion that is expected to throw an error. ```javascript enforce('Bravo').isNotValueOf({ a: 'Alpha', b: 'Bravo', c: 'Charlie' }); // throws ``` -------------------------------- ### Is Value Of Object Assertion (Throws) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value exists as a property value within an object. This example demonstrates an assertion that is expected to throw an error. ```javascript enforce('Delta').isValueOf({ a: 'Alpha', b: 'Bravo', c: 'Charlie' }); // throws ``` -------------------------------- ### Migrate to staticSuite for Server-Side Validations (JavaScript/TypeScript) Source: https://github.com/ealush/vest/blob/latest/website/docs/upgrade_guide.md This snippet demonstrates the migration from the older `create` function to the new `staticSuite` export for handling server-side validations in Vest. The `staticSuite` simplifies state management by automatically handling resets. ```diff - import {create} from 'vest'; + import {staticSuite} from 'vest'; - const suite = create(() => {/*...*/}); + const suite = staticSuite(() => /*...*/}); - function ServerValidation() { - suite.reset(); - suite.run(); - } ``` -------------------------------- ### String Parsing Examples: Case Conversion and Word Manipulation Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/data_parsers.md Showcases various string manipulation parsers like `toCamel`, `toPascal`, `toSnake`, and `toKebab` for converting between different casing conventions. It also includes `append`, `prepend`, `replace`, and `replaceAll` for modifying string content. ```javascript enforce.isString().toCamel().parse('hello_world-test'); // → 'helloWorldTest' enforce.isString().toSnake().parse('helloWorld Test'); // → 'hello_world_test' enforce.isString().append('-js').parse('vest'); // → 'vest-js' enforce.isString().replaceAll('vest', 'n4s').parse('vest vest vest'); // → 'n4s n4s n4s' ``` -------------------------------- ### Validate string boundaries with endsWith and startsWith Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Checks if a string ends or starts with specific characters. These methods return true if the condition is met and throw an error otherwise. ```javascript enforce('aba').endsWith('ba'); enforce('for').endsWith('tor'); // throws enforce('aba').startsWith('ab'); enforce('for').startsWith('tor'); // throws ``` -------------------------------- ### String Validation Patterns with Enforce Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce.md Provides examples of common string validation patterns using Vest's Enforce library. Includes checks for non-blank values, email format, and length constraints. ```javascript // Required field enforce(email).isNotBlank(); // Email format enforce(email).isEmail(); // Length constraints enforce(password).longerThanOrEquals(8).shorterThanOrEquals(128); ``` -------------------------------- ### Is Not Key Of Object Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value does not exist as a key within an object. This example demonstrates successful assertions, including checks against non-object types. ```javascript enforce('avocados').isNotKeyOf({ cantelopes: 5 }); enforce(1967).isNotKeyOf({ 1988: 'Rain Man' }); enforce('key').isNotKeyOf(undefined); enforce(15).isNotKeyOf(null); enforce('star').isNotKeyOf(false); enforce('triangle').isNotKeyOf(true); // passes ``` -------------------------------- ### Vest isDate Rule Example Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/date.md Demonstrates how to use the isDate rule from Vest to validate date strings. It shows basic usage and how to apply custom options like format, strictMode, and delimiters for more precise validation. ```javascript import { enforce } from 'vest'; import 'vest/date'; const dateString = '2002-07-15'; // Basic usage enforce(dateString).isDate(); // Usage with options enforce(dateString).isDate({ format: 'YYYY-MM-DD', strictMode: true, delimiters: ['-', '/'], }); ``` -------------------------------- ### Is Key Of Object Assertion (Passes) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce_rules.md Checks if a given value exists as a key within an object. Handles both string and numeric keys. This example demonstrates successful assertions. ```javascript enforce('bananas').isKeyOf({ bananas: 5 }); enforce(1976).isKeyOf({ 1976: 'Rocky' }); // passes ``` -------------------------------- ### Creating Custom Validation Rules with Enforce Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/enforce.md Explains how to extend Vest's Enforce library with custom validation logic. The example adds a `isValidUsername` rule using `enforce.extend` for custom pattern matching. ```javascript import { enforce } from 'vest'; enforce.extend({ isValidUsername(value) { return /^[a-zA-Z0-9_]+$/.test(value); }, }); // Now use it anywhere enforce(username).isValidUsername(); ``` -------------------------------- ### Conditionally Include Fields in Vest.js Validation Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Demonstrates how to conditionally include specific fields for Vest.js validation using the `only()` function. The example shows how to pass a field name conditionally to `only()`. ```javascript only(hasPromo && 'promo'); ``` -------------------------------- ### Chaining multiple parsers for data transformation (JavaScript) Source: https://github.com/ealush/vest/blob/latest/website/docs/enforce/builtin-enforce-plugins/data_parsers.md Demonstrates chaining multiple parsers together to create a data transformation pipeline. Each parser operates on the output of the previous one, allowing for complex validation and transformation logic. This example shows trimming strings, converting types, clamping numbers, deduplicating arrays, parsing JSON, and providing defaults. ```javascript const schema = enforce.shape({ name: enforce.isString().trim().toTitle(), age: enforce.isNumeric().toNumber().clamp(0, 120), subscribed: enforce.isString().trim().toBoolean(), tags: enforce.isArray().uniq().join('|'), payload: enforce.isString().parseJSON(), nickname: enforce.isString().trim().defaultTo('N/A'), }); schema.parse({ name: ' jANE DOE ', age: '180', subscribed: ' yes ', tags: ['vest', 'n4s', 'vest'], payload: '{"env":"test"}', nickname: ' ', }); // → { // name: 'Jane Doe', // age: 120, // subscribed: true, // tags: 'vest|n4s', // payload: { env: 'test' }, // nickname: '', // } ``` -------------------------------- ### Managing Warnings in Async Tests Source: https://github.com/ealush/vest/blob/latest/website/static/llms-full.txt Demonstrates the correct usage of warn() in synchronous code and useWarn() for asynchronous test flows to ensure warnings are captured correctly. ```javascript // Correct usage in sync/async tests test('password', async () => { warn(); return await someAsyncFunction(); }); // Correct usage with useWarn for async flow test('password', async () => { const setWarn = useWarn(); await someAsyncFunction(); setWarn(); enforce(passwordStrength).isNotWeak(); }); ``` -------------------------------- ### Vest Suite Example with Groups and Focused Runs - JavaScript Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_your_suite/focused_updates.md Demonstrates a Vest validation suite with multiple groups and how to use skipGroup to selectively run or skip entire sections of validation logic based on the context (e.g., sign-in vs. sign-up). ```javascript import { create, test, group, enforce } from 'vest'; const suite = create(data => { test('username', 'Username is required', () => { enforce(data.username).isNotBlank(); }); group('signIn', () => { test('password', 'Password is required', () => { enforce(data.password).isNotBlank(); }); }); group('signUp', () => { test('email', 'Email is required', () => { enforce(data.email).isEmail(); }); test('tos', 'You must accept the terms', () => { enforce(data.tos).equals(true); }); }); }); // When signing in, skip the signUp group entirely suite.focus({ skipGroup: 'signUp' }).run(formData); // When signing up, skip the signIn group entirely suite.focus({ skipGroup: 'signIn' }).run(formData); // Skip multiple groups at once suite.focus({ skipGroup: ['signIn', 'signUp'] }).run(formData); ``` -------------------------------- ### Validating All Fields with run() Source: https://github.com/ealush/vest/blob/latest/website/docs/writing_your_suite/focused_updates.md Demonstrates how to validate all fields in a Vest suite by calling .run() without any focus modifiers. Provides examples for form submission and focused blur validation. ```javascript // Validate all fields on submit function handleSubmit(formData) { suite.afterEach(() => setResult(suite.get())).run(formData); } // Or for focused blur validation function handleBlur(fieldName, value) { suite .only(fieldName) .afterEach(() => setResult(suite.get())) .run({ ...formData, [fieldName]: value }); } ```