Skip to content

Add WithState(...) overload which allows accessing ValidationContext<T> #2276

@ChThy

Description

@ChThy

Is your feature request related to a problem? Please describe.

When using custom ValidationContexts, it is currently not possible to access addional properties on these ValidationContexts when using WithState(...) to customize the validation message.

Describe the solution you'd like

Adding an overload of the WithState(...) method to DefaultValidatorOptions class which takes in a Func<T, TProperty, ValidationContext<T>, object> as stateProvider.

This seems like low hanging fruit since the ValidationContext is available there. Tried adding the function below to DefaultValidatorOptions class and everything builds and all tests run green (Code changes are ready and I am willing to open a pull request):

public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, TProperty, ValidationContext<T>, object> stateProvider) {
  stateProvider.Guard("A lambda expression must be passed to WithState", nameof(stateProvider));

  var wrapper = new Func<ValidationContext<T>, TProperty, object>((ctx, val) => {
    return stateProvider(ctx.InstanceToValidate, val, ctx);
  });

  Configurable(rule).Current.CustomStateProvider = wrapper;
  return rule;
}

Describe alternatives you've considered

The alternative approach that I went for is a custom extension method which mimics WithState(...) and passes the ValidationContext in the stateProvider argument. (Almost the exact same extension method as above)

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions