Created
April 11, 2017 13:11
-
-
Save StevenSwann/731d8e0b6a0ae0ec8b0d26043e9b2535 to your computer and use it in GitHub Desktop.
Data Annotation Custom Validation Allowed File Extentions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)")]