Skip to content

Instantly share code, notes, and snippets.

@matthewsinex
Last active April 30, 2018 19:10
Show Gist options
  • Save matthewsinex/d85e2a22ffe5042a47f64ca1556191b7 to your computer and use it in GitHub Desktop.
Save matthewsinex/d85e2a22ffe5042a47f64ca1556191b7 to your computer and use it in GitHub Desktop.
ASP.NET MVC 5 Custom File DataAnnotation
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace TestProjectMVC5.Models
{
public class FileAttribute : ValidationAttribute
{
public string[] FileTypes { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is HttpPostedFileBase)
{
return ValidateSingleFile((HttpPostedFileBase)value);
}
else if (value is IEnumerable<HttpPostedFileBase>)
{
var propertyInfo = validationContext.ObjectType.GetProperty(validationContext.MemberName);
var isRequired = propertyInfo.CustomAttributes.Where(x => x.AttributeType == typeof(RequiredAttribute)).FirstOrDefault() != null;
return ValidateMultipleFiles(value, isRequired);
}
else
{
return new ValidationResult("The input type is not a file.");
}
}
private ValidationResult ValidateSingleFile(HttpPostedFileBase file)
{
if (!isFileAllowedType(file))
{
return DisallowedFileTypeError(file);
}
return ValidationResult.Success;
}
private ValidationResult ValidateMultipleFiles(object value, bool isRequired)
{
IEnumerable<HttpPostedFileBase> files = (IEnumerable<HttpPostedFileBase>)value;
if (isRequired && files.ToList()[0] == null)
{
return new ValidationResult("No files found.");
}
foreach (var file in files)
{
if (!isFileAllowedType(file))
{
return DisallowedFileTypeError(file);
}
}
return ValidationResult.Success;
}
private bool isFileAllowedType(HttpPostedFileBase file)
{
string fileType = file.ContentType.ToLower();
return FileTypes.Length == 0 || FileTypes.Contains(fileType);
}
private ValidationResult DisallowedFileTypeError(HttpPostedFileBase file)
{
string fileName = file.FileName;
return new ValidationResult($"{ fileName } is not an allowed file type.");
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace TestProjectMVC5.Models
{
public class ImageUpload
{
public string Title { get; set; }
[File(FileTypes = new string[] { "image/png", "image/jpeg", "image/jpg", "image/gif" } )]
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment