如何使用FluentValidation验证上传的文件?
<input type="file" asp-for="Files" multiple />
答案 0 :(得分:5)
您的ViewModel
必须具有public IList<IFormFile> Files { get; set; }
:
public class CustomViewModel
{
public IList<IFormFile> Files { get; set; }
...
}
您必须为IFormFile
类型创建一个验证器,如下所示:
public class FileValidator : AbstractValidator<IFormFile>
{
public FileValidator()
{
RuleFor(x => x.Length).NotNull().LessThanOrEqualTo(100)
.WithMessage("File size is larger than allowed");
RuleFor(x => x.ContentType).NotNull().Must(x => x.Equals("image/jpeg") || x.Equals("image/jpg") || x.Equals("image/png"))
.WithMessage("File type is larger than allowed");
...
}
}
现在您可以像这样在FileValidator
中使用CustomValidator
:
public class CustomValidator : AbstractValidator<CustomViewModel>
{
public CustomValidator()
{
RuleForEach(x => x.Files).SetValidator(new FileValidator());
}
}