Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active January 9, 2024 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/f2ba959b92d16cba8265e7c9b9ea957b to your computer and use it in GitHub Desktop.
Save dj-nitehawk/f2ba959b92d16cba8265e7c9b9ea957b to your computer and use it in GitHub Desktop.
Request DTO inheritance with Validator composition
public class BaseRequest
{
public string? Id { get; init; }
}
public class BaseRequestValidator : Validator<BaseRequest>
{
public BaseRequestValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage("id is required!")
.Must(x => Guid.TryParse(x, out _)).WithMessage("must be a valid guid!");
}
}
public class Request : BaseRequest
{
public string? Title { get; set; }
}
public class RequestValidator : Validator<Request>
{
public RequestValidator()
{
Include(new BaseRequestValidator()); //include the validator for the base dto
RuleFor(x => x.Title).NotEmpty().WithMessage("title is required!");
}
}
public class Endpoint : Endpoint<Request>
{
public override void Configure()
{
Post("test");
AllowAnonymous();
}
public override async Task HandleAsync(Request r, CancellationToken c)
{
await SendAsync(r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment