Skip to content

Instantly share code, notes, and snippets.

@StevenSwann
Created April 11, 2017 13:11
Show Gist options
  • Save StevenSwann/731d8e0b6a0ae0ec8b0d26043e9b2535 to your computer and use it in GitHub Desktop.
Save StevenSwann/731d8e0b6a0ae0ec8b0d26043e9b2535 to your computer and use it in GitHub Desktop.
Data Annotation Custom Validation Allowed File Extentions
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class AllowedFileExtensionsAttribute : ValidationAttribute
{
private List<string> AllowedExtensions { get; set; }
public AllowedFileExtensionsAttribute(string fileExtensions)
{
AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public override bool IsValid(object value)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file != null)
{
var fileName = file.FileName;
return AllowedExtensions.Any(y => fileName.EndsWith(y));
}
return true;
}
}
@StevenSwann
Copy link
Author

Only allows certain file types to be uploaded.
Usage example: [AllowedFileExtensions("jpg,jpeg,png,gif", ErrorMessage = "Please select a valid file type. (.jpg, .jpeg, .png or .gif)")]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment