Libraries (v1.1.10)
    Preparing search index...

    Class ObjectSchemaBuilder<TProperties, TRequired, TExplicitType>

    Object schema builder class. Similar to the object type in JS. Allows to define a schema for object value. Should be used to validate objects with specific properties. Properties should be defined as their own schema builders. You can use any SchemaBuilder e.g. string(), number(), boolean(), array(), object(), etc. to define properties. Which means that you can define nested objects and arrays of any complexity.

    NOTE this class is exported only to give opportunity to extend it by inheriting. It is not recommended to create an instance of this class directly. Use object() function instead.

    const schema = object({
    name: string(),
    age: number()
    });

    const result = await schema.validate({
    name: 'John',
    age: 30
    });

    // result.valid === true
    // result.object === { name: 'John', age: 30 }
    const schema = object({
    name: string(),
    age: number().optional()
    });

    const result = await schema.validate({
    name: 'John'
    });
    // result.valid === true
    // result.object === { name: 'John' }
    const schema = object({
    name: string(),
    age: number();
    });
    const result = await schema.validate({
    name: 'John'
    });

    // result.valid === false
    // result.errors is deprecated — use result.getErrorsFor() instead
    // result.getErrorsFor((p) => p.age).errors // ["is expected to have property 'age'"]
    const schema = object({
    name: string(),
    address: object({
    city: string(),
    country: string()
    })
    });
    const result = await schema.validate({
    name: 'John',
    address: {
    city: 'New York',
    country: 'USA'
    }
    });
    // result.valid === true
    // result.object === {
    // name: 'John',
    // address: {
    // city: 'New York',
    // country: 'USA'
    // }
    // }

    object

    Type Parameters

    • TProperties extends Record<string, SchemaBuilder<any, any>> = {}
    • TRequired extends boolean = true
    • TExplicitType = undefined

    Hierarchy (View Summary)

    Index

    Accessors

    • get isRequired(): TRequired

      Whether the schema requires a non-null/non-undefined value.

      Returns TRequired

    • set isRequired(value: boolean): void

      Sets the requirement flag. Must be a boolean.

      Parameters

      • value: boolean

      Returns void

    • get preprocessors(): Preprocessor<TResult>[]

      A list of preprocessors associated with the Builder

      Returns Preprocessor<TResult>[]

    • get validators(): Validator<TResult>[]

      A list of validators associated with the Builder

      Returns Validator<TResult>[]

    Methods

    • Ensures a ValidationErrorMessageProvider is valid. If provider is undefined, falls back to defaultValue. Function providers are bound to this for access to schema state.

      Parameters

      • provider: ValidationErrorMessageProvider<any> | undefined

        the provider to validate, or undefined

      • defaultValue: ValidationErrorMessageProvider<any>

        fallback provider when provider is not supplied

      Returns ValidationErrorMessageProvider<any>

      a valid ValidationErrorMessageProvider

    • Protected method used to create a new instance of the Builder defined by the props object. Should be used to instantiate new builders to keep builder's immutability.

      Type Parameters

      • T extends Record<string, SchemaBuilder<any, true>>
      • R extends boolean = true

      Parameters

      • props: ObjectSchemaBuilderCreateProps<T, R>

        arbitrary props object

      Returns this

    • Resolves a ValidationErrorMessageProvider to a string error message. Handles both string providers and function providers (sync or async).

      Parameters

      • provider: ValidationErrorMessageProvider<any>

        the error message provider (string or function)

      • seenValue: undefined extends TExplicitType
            ? RespectPropsOptionality<TProperties>
            : TExplicitType

        the value that caused the validation error

      Returns Promise<string>

      the resolved error message string

    • Generates a serializable object describing the defined schema

      Returns {
          acceptUnknownProps: boolean;
          isRequired: boolean;
          preprocessors: readonly Preprocessor<
              undefined extends TExplicitType
                  ? RespectPropsOptionality<TProperties>
                  : TExplicitType,
          >[];
          properties: TProperties;
          requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<
              SchemaBuilder<any, any>,
          >;
          type: string;
          validators: readonly Validator<
              undefined extends TExplicitType
                  ? RespectPropsOptionality<TProperties>
                  : TExplicitType,
          >[];
      }

      • acceptUnknownProps: boolean

        If set to true, schema validation will not return errors if object contains fields which are not defined in the schema properties. Set to false by default

      • isRequired: boolean

        If set to false, schema will be optional (null or undefined values will be considered as valid).

      • preprocessors: readonly Preprocessor<
            undefined extends TExplicitType
                ? RespectPropsOptionality<TProperties>
                : TExplicitType,
        >[]

        Array of preprocessor functions

      • properties: TProperties

        Properties defined in schema

      • requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<SchemaBuilder<any, any>>

        Custom error message provider for the 'is required' validation error.

      • type: string

        String id of schema type, e.g. string', numberorobject`.

      • validators: readonly Validator<
            undefined extends TExplicitType
                ? RespectPropsOptionality<TProperties>
                : TExplicitType,
        >[]

        Array of validator functions

    • Runs preprocessors, validators, and the required/optional check on object. Subclasses call this at the start of their validate() implementation to get a preprocessed value wrapped in a transaction, along with any early errors.

      Parameters

      Returns Promise<
          PreValidationResult<
              TRequired extends true
                  ? undefined extends TExplicitType
                      ? Id<RespectPropsOptionality<TProperties>>
                      : TExplicitType
                  :
                      | (
                          undefined extends TExplicitType
                              ? Id<RespectPropsOptionality<TProperties>>
                              : TExplicitType
                      )
                      | undefined,
              { validatedObject: any },
          >,
      >

      a PreValidationResult containing the preprocessed transaction, context, and any errors