I'm having an issue implementing a custom ValidationAttribute
which requires both client and server validation. When ran strictly on the server, it passes and fails validation as expected, but the error message is not sent back to the client. Everything works fine on the client.
Attribute
public class MaxFileSizeAttribute : ValidationAttribute, IClientValidatable
{
private int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
public override bool IsValid(object value)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
return file.ContentLength <= _maxFileSize;
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(_maxFileSize.ToString());
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(_maxFileSize.ToString()),
ValidationType = "filesize"
};
rule.ValidationParameters["maxsize"] = _maxFileSize;
yield return rule;
}
}
The view includes:
@Html.ValidationMessageFor(model => model.File)
@Html.TextBoxFor(model => model.File, new { type="file", style="width:79%", placeholder="Select CSV or TXT file for upload"})
And the relevant parts of the ViewModel
[MaxFileSize(10 * 1024 * 1024, ErrorMessage="File size must be less than 10mb")]
public HttpPostedFileBase File { get; set; }