How to validate uploaded files by FluentValidation

喜你入骨 提交于 2019-12-24 17:10:31

问题


How can I validate uploaded files using FluentValidation?

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


回答1:


your ViewModel must have public IList<IFormFile> Files { get; set; } :

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

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

               ...
        }
    }

now you can use FileValidator in your CustomValidator like this:

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


来源:https://stackoverflow.com/questions/59358252/how-to-validate-uploaded-files-by-fluentvalidation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!