Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileExtensions attribute of DataAnnotations not working in MVC

I am trying to upload a file using HTML FileUpload control in MVC. I want to validate the file to accept only specific extensions. I have tried using FileExtensions attribute of DataAnnotations namespace, but its not working. See code below -

public class FileUploadModel
    {
        [Required, FileExtensions(Extensions = (".xlsx,.xls"), ErrorMessage = "Please select an Excel file.")]
        public HttpPostedFileBase File { get; set; }
    }

In the controller, I am writing the code as below -

[HttpPost]
        public ActionResult Index(FileUploadModel fileUploadModel)
        {
            if (ModelState.IsValid)
                fileUploadModel.File.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(fileUploadModel.File.FileName)));

            return View();
        }

In View, I have written below code -

@using (Html.BeginForm("Index", "FileParse", FormMethod.Post, new { enctype = "multipart/form-data"} ))
{
    @Html.Label("Upload Student Excel:")
    <input type="file" name="file" id="file"/>
    <input type="submit" value="Import"/>
    @Html.ValidationMessageFor(m => m.File)
}

When i run the application and give an invalid file extension, its not showing me the error message. I am aware of solution to write custom validation attribute, but I dont want to use custom attribute. Please point out where I am going wrong.

like image 891
DfrDkn Avatar asked Jul 12 '15 09:07

DfrDkn


People also ask

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

What is the namespace for DataAnnotations in MVC?

The namespace System. ComponentModel. DataAnnotations, has a group of classes, attributes and methods, to make validations in our . NET applications.

What is data annotation validator attributes in MVC?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.


1 Answers

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 image 77
Rafael Botelho Avatar answered Sep 28 '22 09:09

Rafael Botelho