ValidateMeta<T>

Tests metadata for existence, typing, and supplied assertions.
This module performs tests on metadata. It can ensure metadata exists, that it can be converted to the correct type, and that is passes arbitrary tests (delegates) to ensure validity. Metadata can be specified as optional, in which case, typing and assertion testing will only be run if the metadata exists. If any check fails, this module throws an exception with a descriptive error message then halts further execution.

Examples

This example will ensure "Title" exists. (It will also perform a type check, but since "object" matches anything, the type check will always succeed.)
ValidateMeta<object>("Title")
This example will ensure that if "Date" exists, it can convert to a valid DateTime.
ValidateMeta<DateTime>("Date")
   .IsOptional()
This example will ensure "Age" (1) exists, (2) can convert to an integer, (3) and is greater than 0 and less than 121. If it fails any assertion, the provided error message will be output. (In this case, those two assertions could be rolled into one, but then they would share an error message. Separate assertions allow more specific error messages.) Assertions will be checked in order. Any assertion can assume all previous assertions have passed. Error messages will be appended with the document Source and Id properties to assist in identifying invalid documents.
ValidateMeta<int>("Age")
   .WithAssertion(a => a > 0, "You have to be born.")
   .WithAssertion(a => a <= 120, "You are way, way too old.")

Usage

  • ValidateMeta(string key)

    Performs validation checks on metadata.

    • key

      The meta key representing the value to test.

Fluent Methods

Chain these methods together after the constructor to modify behavior.

  • IsOptional()

    Declares the entire check as optional. Is this is set, and the meta key doesn't exist, no checks will be run.

  • WithAssertion(Func<, > execute, string message = null)

    Performs validation checks on metadata.

    • execute

      The assertion function, of type Func<T, bool> where T is the generic parameter of the ValidateMeta declaration. Assertions are strongly-typed and can assume the value has been converted to the correct type. If the function returns false, the check failed, an exception will be thrown, and execution will halt.

    • message

      The error message to output on failure.

GitHub