title: How to validate file type of HttpPostedFileBase attribute in Asp.Net MVC 4?
body: <p>I'm trying validate a file type of <code>HttpPostedFileBase</code> attribute to check type of file but I can't do this because the validation is passing. How could I do this ?</p>
  
  <p>trying</p>
  
  <p><strong>Model</strong></p>
  
  <pre><code>public class EmpresaModel{
  
  [Required(ErrorMessage="Choose a file .JPG, .JPEG or .PNG file")]
  [ValidateFile(ErrorMessage = "Please select a .JPG, .JPEG or .PNG file")]
  public HttpPostedFileBase imagem { get; set; }
  
  }
  </code></pre>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;div class="form-group"&gt;
        &lt;label for="@Html.IdFor(model =&gt; model.imagem)" class="cols-sm-2 control-label"&gt;Escolha a imagem &lt;img src="~/Imagens/required.png" height="6" width="6"&gt;&lt;/label&gt;
         @Html.TextBoxFor(model =&gt; Model.imagem, new { Class = "form-control", placeholder = "Informe a imagem", type = "file" })
         @Html.ValidationMessageFor(model =&gt; Model.imagem)
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>ValidateFileAttribute</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.Drawing;
  using System.Drawing.Imaging;
  using System.Linq;
  using System.Web;
  
  //validate file if a valid image
  public class ValidateFileAttribute : RequiredAttribute{
  
      public override bool IsValid(object value)
      {
          bool isValid = false;
          var file = value as HttpPostedFileBase;
  
          if (file == null || file.ContentLength &gt; 1 * 1024 * 1024)
          {
              return isValid;
          }
  
          if (IsFileTypeValid(file))
          {
              isValid = true;
          }
  
          return isValid;
      }
  
      private bool IsFileTypeValid(HttpPostedFileBase file)
      {
          bool isValid = false;
  
          try
          {
              using (var img = Image.FromStream(file.InputStream))
              {
                  if (IsOneOfValidFormats(img.RawFormat))
                  {
                      isValid = true;
                  } 
              }
          }
          catch 
          {
              //Image is invalid
          }
          return isValid;
      }
  
      private bool IsOneOfValidFormats(ImageFormat rawFormat)
      {
          List&lt;ImageFormat&gt; formats = getValidFormats();
  
          foreach (ImageFormat format in formats)
          {
              if(rawFormat.Equals(format))
              {
                  return true;
              }
          }
          return false;
      }
  
      private List&lt;ImageFormat&gt; getValidFormats()
      {
          List&lt;ImageFormat&gt; formats = new List&lt;ImageFormat&gt;();
          formats.Add(ImageFormat.Png);
          formats.Add(ImageFormat.Jpeg);        
          //add types here
          return formats;
      }
  
  
  }
  </code></pre>