I'm trying to validate file size using FluentValidation in ASP.Net Core 3.1, and it works properly, but the property name generated looks like this:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|f885b78f-4a52ff23c676c331.",
"errors": {
"MyFile.Length": [
"My file: The max file size allowed is 5 Mb."
]
}
}
The problem is that property name generated is "MyFile.Length"
and I would like that the result was only "MyFile"
. My current code is:
InsertMovementValidator.cs
public class InsertMovementValidator : AbstractValidator<InsertMovementDTO>
{
public InsertMovementValidator ()
{
RuleFor(x => x.MyFile).SetValidator(new FileValidator());
}
}
FileValidator.cs
public class FileValidator : AbstractValidator<IFormFile>
{
public FileValidator()
{
RuleFor(x => x.Length).LessThanOrEqualTo(5242880) //5 Megabytes
.WithName("My file")
.WithMessage("{PropertyName}: The max file size allowed is 5 Mb");
}
}
Thanks in advance.
You can set the Validator like below:
public class InsertMovementValidator : AbstractValidator<InsertMovement>
{
public InsertMovementValidator()
{
RuleFor(x => x.MyFile).SetValidator(new FileValidator()).OverridePropertyName("");
}
}
public class FileValidator : AbstractValidator<IFormFile>
{
public FileValidator()
{
RuleFor(x => x.Length).LessThanOrEqualTo(102400) //100 kb
.OverridePropertyName("My file")
.WithName("My file")
.WithMessage("{PropertyName}: The max file size allowed is 100 Kb");
}
}
Result: