0

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; }
Tom
  • 2,180
  • 7
  • 30
  • 48
  • 1
    Are you sure you followed step by step everything as I described here: http://stackoverflow.com/a/10446355/29407? Because my code works perfectly fine and displays the correct error message. – Darin Dimitrov Jun 17 '13 at 15:00
  • Apparently not, it seems to be a little better after changing the return on my controller. I'm now having an issue where it's being called as soon as the page is loaded for the first time (i.e., I get the validation message before pressing anything); and yes, it's followed step by step – Tom Jun 17 '13 at 17:13

0 Answers0