Custom Functions

Custom functions can be added to a validator when you require specific validation to be performed that is not available as a built-in function.


You can add a custom function via theWith(ValidatorDelegate<T>) method.

The ValidatorDelegate<T> parameter is a delegate type that defines a method signature with a singleValidationContext<T> parameter and returns void.

e.g. void MyValidatorFunc(ValidationContext<int> ctx)
or ctx => {} when using a lambda expression.

Example Usage

Using lambda function (recommended)

var builder = new ValidatorBuilder<int>();

// delegate lambda function added inline
builder.With(ctx => 
{
    // test the value in the context
    if (ctx.Value == 13)
    {
        // add broken rule
        ctx.AddBrokenRule("NotThirteen", "Unlucky", "Value cannot equal 13");
    }
});

Using delegate method

public static class ValidatorFuncs
{
    public static void IntegerValidator(ValidationContext<int> ctx)
    {
        // test the value in the context
        if (ctx.Value == 13)
        {
            // add broken rule
            ctx.AddBrokenRule("NotThirteen", "Unlucky", "Value cannot equal 13");
        }
    }
}

var builder = new ValidatorBuilder<int>();

// delegate method added
builder.With(ValidatorFuncs.IntegerValidator);

See also