Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from ioab/FileMaxSizeAttribute.cs
Created September 25, 2017 01:30
Show Gist options
  • Save LSTANCZYK/5f6729c2109c42e48ce1eb59dd183c90 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/5f6729c2109c42e48ce1eb59dd183c90 to your computer and use it in GitHub Desktop.
File max size validation attribute for ASP.NET MVC
namespace App.Infrastructure
{
public class FileMaxSizeAttribute : ValidationAttribute
{
public FileMaxSizeAttribute(int maxSize = 10 * 1024 * 1024, string errorMessage = "{0} is not a valid file.")
: base(errorMessage)
{
// 10 MB by default //
this._maxSize = maxSize;
}
public override ValidationResult IsValid(object value, ValidationContext context)
{
var file = value as HttpPostedFileBase;
if (file == null || file.ContentLength > _maxSize)
{
return new ValidationResult(FormatErrorMessage(context.DisplayName));
}
return ValidationResult.Success;
}
private readonly float _maxSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment