FileExtensions attribute of DataAnnotations not working in MVC

I had the same problem and I resolved creating a new ValidationAttribute.

Like this:

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileExtensionsAttribute : ValidationAttribute
    {
        private List<string> AllowedExtensions { get; set; }

        public FileExtensionsAttribute(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;
        }
    }

Now, just use this:

[FileExtensions("jpg,jpeg,png,gif", ErrorMessage = "Your error message.")]
public HttpPostedFileBase Imagem { get; set; }

I have helped. Hugs!


Like marai answered, the FileExtension Attribute only works on string properties.

In my code, i use the attribute as follows:

public class MyViewModel
{
    [Required]
    public HttpPostedFileWrapper PostedFile { get; set; }

    [FileExtensions(Extensions = "zip,pdf")]
    public string FileName
    {
        get
        {
            if (PostedFile != null)
                return PostedFile.FileName;
            else
                return "";
         }
    }
}

Then, in server side, ModelState.IsValid will be false if the postedfile doesn't have the entensions that you specify in the attribute (.zip and .pdf in my example).

Note: If you are using the HTML.ValidationMessageFor helper to render the error message after PostBack (The File Extension Attribute does not validate on client side, only server side), you need to specify another helper for the FileName property in order to display the extension error message:

@Html.ValidationMessageFor(m => m.PostedFile)
@Html.ValidationMessageFor(m => m.FileName)

The FileExtensions Attribute does not know how to verify a HttpPostedFileBase. Please try below

[FileExtensions(Extensions = "xlsx|xls", ErrorMessage = "Please select an Excel file.")]
public string Attachment{ get; set; }

In your controller:

[HttpPost]
    public ActionResult Index(HttpPostedFileBase Attachment)
    {
        if (ModelState.IsValid)
        {
            if (Attachment.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("/Content/Upload"), Path.GetFileName(Attachment.FileName));
                Attachment.SaveAs(filePath);
            }
        }
        return RedirectToAction("Index_Ack"});
    }

I used the code above in FileExtensions attribute of DataAnnotations not working in MVC, I just did a couple of changes to: 1)avoid namespace collisions and 2) to use IFormFile instead of the original HttpPostedFileBase. Well, maybe is usefull to someone.

My code:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileVerifyExtensionsAttribute : ValidationAttribute
{
    private List<string> AllowedExtensions { get; set; }

    public FileVerifyExtensionsAttribute(string fileExtensions)
    {
        AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
    }

    public override bool IsValid(object value)
    {
        IFormFile file = value as IFormFile;

        if (file != null)
        {
            var fileName = file.FileName;

            return AllowedExtensions.Any(y => fileName.EndsWith(y));
        }

        return true;
    }
}

Comments

  1. Chris

    • 2015/12/27

    I have tried using FileExtensions attribute of DataAnnotations namespace, but its not working. See code below -

  2. Parisi

    • 2020/10/21

    I used the code above in FileExtensions attribute of DataAnnotations not working in MVC, I just did a couple of changes to: 1)avoid namespace collisions and 2) to use IFormFile instead of the original HttpPostedFileBase. Well, maybe is usefull to someone.

  3. Jesiah

    • 2016/3/4

    I have this property in my ViewModel : [Display(Name = "Images")] It doesn't work on IFormFile properties, and definitely not on 

  4. Greyson

    • 2016/10/22

    file extension data annotations worked only on the string data.i solved this problem with help Validation Attribute that called is custom server side validation. 1.first create a Folder on the root your project called Validation. 2.on this folder create a class called FileExtensionValidation.this like code below:

  5. Parker

    • 2021/3/21

    I am trying to upload a file using HTML FileUpload control in MVC. I want to validate the file to accept only specific extensions.

  6. Aziel

    • 2016/10/9

    Can't get MVC 4 FileExtensions Attribute to work on ViewModel property. Ask Question FileExtensions attribute of DataAnnotations not working in MVC. 3.

  7. Xander

    • 2018/11/23

    I use a wrapper for MVC 4. public class HttpPostedFileExtensionsAttribute file extensions (".png", ".jpg", ".jpeg", and ".gif") if the property is not 

  8. Jovanni

    • 2018/3/26

    It doesn't work on IFormFile properties, and definitely not on IEnumerable<IFormFile> properties. I think that the reason you're seeing it "validate" as invalid is because the attribute returns "invalid" if the property isn't a string.

  9. Fabbri

    • 2020/9/13

    Property Value. String. The file name extensions, or the default file extensions (".png", ".jpg", ".jpeg", and ".gif") if the property is not set.

  10. Bernard

    • 2015/6/11

    The ASP.NET MVC 5 platform already contains a default FileExtensions attribute, but, the issue with this pre-built data annotation/attribute is that it is applicable only on string type view model properties and in my case, I am uploading the files via "HttpPostedFileBase" data type view model property. This means that the pre-built data annotation/attribute does not have any means to know the data type of the file(s) that I am uploading which will have no effect on the limitation that is

  11. Major

    • 2018/11/4

    This means that the pre-built data annotation/attribute does not have while working with the pre-built FileExtensions attribute, but, 

  12. Julio

    • 2017/5/14

    Checks that the specified file name extension or extensions is valid. Validates the specified value with respect to the current validation attribute. When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. Creates a shallow copy of the current Object.

  13. Alvarez

    • 2016/1/10

    I tried uploading a jpg without the attribute, it works. Great. Then I added the attribute to my view model.. [FileExtensions(ErrorMessage = "Please specify a 

  14. Richard

    • 2016/7/29

    Data annotation attributes from System.ComponentModel.DataAnnotations namespace contain a set of attributes that can be used to validate model data in ASP.NET MVC applications. Attributes such as [Required], [StringLength], [Range], [EmailAddress], [Url] and [RegularExpression] cover common validation scenarios.

  15. Benjamin

    • 2020/9/14

    The following table lists all the data annotation attributes which can be used for validation. Attribute, Usage. Required, Specifies that a property value is 

  16. Brandon

    • 2016/4/9

    have tried for valid image format are working with asp.net mvc Data annotations, NET 4.5, you can use the FileExtensions Attribute: 

Comments are closed.

Recent Posts