如何通过FluentValidation验证上传的文件 [英] How to validate uploaded files by FluentValidation

查看:99
本文介绍了如何通过FluentValidation验证上传的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I validate uploaded files using FluentValidation?

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

推荐答案

您的ViewModel必须具有public IList<IFormFile> Files { get; set; }:

    public class CustomViewModel
    {
        public IList<IFormFile> Files { get; set; }
        ...
    }

您必须为IFormFile类型创建一个验证器,如下所示:

you must create a validator for IFormFile type as below:

    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");

               ...
        }
    }

现在您可以像这样在CustomValidator中使用FileValidator:

now you can use FileValidator in your CustomValidator like this:

    public class CustomValidator : AbstractValidator<CustomViewModel>
    {
        public CustomValidator()
        {
            RuleForEach(x => x.Files).SetValidator(new FileValidator());
        }
    }

这篇关于如何通过FluentValidation验证上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆