Immediate.Validations is a source generator validating
Immediate.Handlers handler parameters.
You can install Immediate.Validations with NuGet:
Install-Package Immediate.Validations
Or via the .NET Core command line interface:
dotnet add package Immediate.Validations
Either command, from Package Manager Console or .NET Core CLI, will download and install Immediate.Validations.
Indicate that a class should be validated by adding the [Validate] attribute and IValidationTarget<> interface:
[Validate]publicpartialrecordQuery:IValidationTarget<Query>;When Nullable Reference Types is enabled, any non-nullable reference types are automatically checked for null. Other
validations are available like so:
[Validate]publicpartialrecordQuery:IValidationTarget<Query>{[GreaterThan(0)]publicrequiredintId{get;init;}}Since attributes cannot reference anything other than constant strings, the way to reference static and instance
properties, fields, and methods is to use the nameof() to identify which property, field, or method should be used. Example:
[Validate]publicpartialrecordQuery:IValidationTarget<Query>{[GeneratedRegex(@"^\d+$")]privatestaticpartialRegexAllDigitsRegex();[Match(regex:nameof(AllDigitsRegex))]publicrequiredstringId{get;init;}}Provide a custom message to any validation using the Message property of the attribute. This message will be parsed
for template parameters, which will be applied to the message before rendering to the validation result. The target property
name is available as {PropertyName}, and it's value via {PropertyValue}.
Other parameter values will be added using their property name suffixed with Value (for example, the
GreaterThanAttribute uses a comparison parameter, so the value is available via ComparisonValue). If another
property on the target class is referenced via nameof(Property), the name of that property will be available using the
Name suffix (for example, ComparisonName for the comparison property).
[Validate]publicpartialrecordQuery:IValidationTarget<Query>{[GreaterThan(0,Message="'{PropertyName}' must be greater than '{ComparisonValue}'")]publicrequiredintId{get;init;}}If attributes are not enough to specify how to validate a class, an AdditionalValidations method can be used to write
additional validations for the class.
[Validate]publicpartialrecordQuery:IValidationTarget<Query>{publicrequiredboolEnabled{get;init;}publicrequiredintId{get;init;}privatestaticvoidAdditionalValidations(ValidationResulterrors,Querytarget){if(target.Enabled){// Use a lambda to use the default message or override message;// the message will be templated in the same way as attribute validations.errors.Add(()=>GreaterThanAttribute.ValidateProperty(target.Id,0));}if(false){// Manually create a `ValidationError` and add it to the `ValidationResult`.errors.Add(newValidationError(){PropertyName="ExampleProperty",ErrorMessage="Example Message",})}}}An instance of an IV object can be validated directly by calling ClassName.Validate(instance);. In the example above,
this would look like:
publicvoidMethod(Queryquery){varresults=Query.Validate(query);}The results object will contain information on whether the instance is valid, and if not, the validation failures that
occurred during validation.
If you would like to throw an exception if the validation fails, you can call ValidationException.ThrowIfInvalid(). This
method can be called using the ValidationResult returned from validation if you have already validated it, or using an
instance of the object if you would like to validate and throw. Examples:
publicvoidMethod(Queryquery){varresults=Query.Validate(query);ValidationException.ThrowIfInvalid(results);// orValidationException.ThrowIfInvalid(query);}Using Immediate.Validations with Immediate.Handlers
Adding code to explicitly validate the object in every method that needs to do so can be annoying. Immediate.Validations
is intended to integrate primarily with Immediate.Handlers, and so it provides an IH Behavior<,> which can be used to
automatically add validation to every IH handler which has a request which is an IValidation<> object. Add
Immediate.Validations to the Immediate.Handlers behaviors pipeline by including it in the list of default Behaviors for
the assembly:
usingImmediate.Validations.Shared;[assembly:Behaviors(typeof(ValidationBehavior<,>))]The result of doing the above is that when a parameter fails one or more validations, a ValidationException is thrown,
which can be handled via ProblemDetails or any other infrastructure mechanism.
Example using ProblemDetails:
builder.Services.AddProblemDetails(ConfigureProblemDetails);publicstaticvoidConfigureProblemDetails(ProblemDetailsOptionsoptions)=>options.CustomizeProblemDetails= c =>{if(c.Exceptionisnull)return;c.ProblemDetails=c.Exceptionswitch{ValidationExceptionex=>newValidationProblemDetails(ex.Errors.GroupBy(x =>x.PropertyName,StringComparer.OrdinalIgnoreCase).ToDictionary(
x =>x.Key,
x =>x.Select(x =>x.ErrorMessage).ToArray(),StringComparer.OrdinalIgnoreCase)){Status=StatusCodes.Status400BadRequest,},// other exception handling as desiredvarex=>newProblemDetails{Detail="An error has occurred.",Status=StatusCodes.Status500InternalServerError,},};c.HttpContext.Response.StatusCode=c.ProblemDetails.Status??StatusCodes.Status500InternalServerError;};