-
-
Save LSTANCZYK/5f6729c2109c42e48ce1eb59dd183c90 to your computer and use it in GitHub Desktop.
File max size validation attribute for ASP.NET MVC
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
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