Created New Validation Library that Integrates with Vogen #874
CodingFlow
started this conversation in
Show and tell
Replies: 1 comment 2 replies
-
|
I did a similar thing yesterday but using the FluentValidation library directly and with source generation. Not used in real-world applications yet. It should help with #866 too. Generic code: public abstract class VogenValidator<T> : AbstractValidator<T>
{
public sealed override Task<ValidationResult> ValidateAsync(ValidationContext<T> context, CancellationToken cancellation = default)
{
throw new Exception("Vogen value objects cannot be validated asynchronously.");
}
}
public static class VogenUtil
{
public static Validation Validate<TValidator, TProperty>(TProperty value)
where TValidator : VogenValidator<TProperty>, new()
{
ValidationResult validationResult = new TValidator().Validate(value);
if (!validationResult.IsValid)
return Validation.Invalid(string.Join(", ", validationResult.Errors.Select(e => e.ErrorMessage)));
return Validation.Ok;
}
}Use case: [ValueObject<int>]
[LessThanOrEqual(120, WithMessage = "Age must be 120 or less")]
public readonly partial struct Age
{
private static Validation Validate(in int value) => VogenUtil.Validate<AgeValidator, int>(value);
}Source generated code: public partial class AgeValidator : VogenValidator<int>
{
public AgeValidator()
{
RuleFor(x => x)
.LessThanOrEqualTo(120).WithMessage("Age must be 120 or less")
;
ConfigureAdditionalRules();
}
partial void ConfigureAdditionalRules();
}Need anything special? public partial class AgeValidator
{
partial void ConfigureAdditionalRules()
{
// complex custom rule example
}
}Your idea is similar and should work well, I'm not sure you want to maintain a whole new validation library, maybe a wrapper for an existing robust validation library is more sustainable |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone. I've created a new fluent API validation library that integrates with Vogen, CodingFlow.FluentValidation. Here is a quick sample of what it looks like:
I hope this is useful to someone. Let me know what you think!
Beta Was this translation helpful? Give feedback.
All reactions