如何使用FluentValidation验证上传的文件?
<input type="file" asp-for="Files" multiple />
如何使用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
类型的验证器,如下所示:
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
:
public class CustomValidator : AbstractValidator<CustomViewModel>
{
public CustomValidator()
{
RuleForEach(x => x.Files).SetValidator(new FileValidator());
}
}