'FluentValidation show object errors in one array - .Net 5.0
How to show object errors in one array in Fluent Validation?
{
"Succeeded": false,
"Message": "Error",
"Errors": [
"[0].Must be Greater Than Zero",
"[0].Cannot be Null"
],
"Data": null
}
to
{
"Succeeded": false,
"Message": "Error",
"Errors": [
"[0]": [
"Must be Greater Than Zero",
"Cannot be Null"
]
],
"Data": null
}
How to collect errors of object in one array. I want to return Validation error response something in second example. this is my FluentValidation class
public class InvoiceValidator : BaseValidator<InvoiceDTO>
{
RuleFor(x => x.taxId)
.Cascade(CascadeMode = CascadeMode.Continue)
.NotEmpty().WithMessage(x => $"[{x.checkNo}].not empty
.Length(10).WithMessage(x => $"[{x.checkNo}].max 10");
RuleFor(x => x.companyName)
.Cascade(CascadeMode = CascadeMode.Continue)
.NotEmpty().WithMessage(x => $"[{x.checkNo}].not Empty")
.Length(3, 150).WithMessage(x => $"[{x.checkNo}].between 3-150");
}
And its exception when validation is not valid
public class ValidateException : Exception
{
public List<string> Errors { get; }
public ValidateException() : base("One or more errors")
{
Errors = new List<string>();
}
public ValidateException(IEnumerable<ValidationFailure> failures) : this()
{
foreach (var item in failures)
{
Errors.Add(item.ErrorMessage);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
