Strickland
  • Readme
  • Introduction
    • Validators
    • Validation
    • Validation Results
  • Extensibility
    • Validator Factories
    • Validation Context
    • Validation Result Props
    • Extensibility Pattern
    • formatResult
  • Built-In Validators
    • required
    • compare
    • min
    • max
    • range
    • minLength
    • maxLength
    • length
  • Composition
    • Arrays of Validators
      • every
      • all
      • some
    • Validating Array Elements
      • arrayElements
    • Validating Objects
      • objectProps
      • Advanced Object Validation
      • Nested Objects
      • Arrays of Objects
    • Composition Conventions
    • Composition and formatResult
  • Async Validation
    • Resolving Async Validation
    • Deferred Async Validation
    • Async Validator Arrays and Objects
    • Two-Stage Sync/Async Validation
    • Race Conditions
    • Automatic Race Condition Handling
    • Async Validation and formatResult
  • Form Validation
    • form
    • Async Form Validation
    • validateFields
    • emptyResults
    • updateFieldResults
  • Inspiration
  • Design Goals
  • Wrap-Up
  • Change Log
  • NPM
  • GitHub
Powered by GitBook
On this page

Was this helpful?

  1. Async Validation

Deferred Async Validation

When a validator returns a Promise, the Promise will begin resolution immediately, before the application invokes the validateAsync function. This is desired in some cases to begin resolving async validation eagerly so that async results are ready when validateAsync() is invoked. In other cases, the application may not call validateAsync until later in the workflow and the initial async result might not even be consumed.

To defer async validation until validateAsync() is called, validators can return a function that returns the async validation result Promise. Let's modify the usernameIsAvailable validator to defer async validation in this way.

import validate from 'strickland';

function usernameIsAvailableDeferred(username) {
    return function validateUsernameAsync() {
        return new Promise((resolve) => {
            if (username === 'marty') {
                // Resolve to an invalid validation result object
                resolve({
                    isValid: false,
                    message: `"${username}" is not available`
                });
            }

            // Resolve to a boolean
            resolve(true);
        });
    }
}

const result = validate(usernameIsAvailableDeferred, 'marty');

result.validateAsync().then((asyncResult) => {
/*
    asyncResult = {
        isValid: false,
        value: 'marty',
        message: '"marty" is not available'
    }
 */
});

Aside from the validator returning a function, the rest of the workflow is exactly the same, and this was completely transparent to the application.

PreviousResolving Async ValidationNextAsync Validator Arrays and Objects

Last updated 4 years ago

Was this helpful?