如何通过FluentValidation验证上传的文件

时间:2019-12-16 14:04:30

标签: asp.net-core model-view-controller file-upload fluentvalidation

如何使用FluentValidation验证上传的文件?

      <input type="file" asp-for="Files" multiple />

1 个答案:

答案 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());
        }
    }