1

In my MVC web application, I have a form with a imageupload component. The imageupload Image-data is validated with help of data-annotation. My server side validation is WORKING, but my client side jQuery function is not being called ... I don't know why- HELP:

1. File-upload in my View:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

<input type="file" id="FileUploader" name="FileUploader" multiple />
<div id="FileDisplay" name="FileDisplay"></div>
@Html.ValidationMessageFor(model => model.FileUploader, "", new { @class = "text-danger" })

2. In my Model, i have this:

[ValidImageUpload]
public IEnumerable<HttpPostedFileBase> FileUploader { get; set; }

3.ValidImageUpload file:

public sealed class ValidImageUpload : ValidationAttribute, IClientValidatable
{
    string[] stringArray = { "gif", "jpg", "png", "jpeg" };

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        IEnumerable<System.Web.HttpPostedFileBase> uploadedFiles = (IEnumerable<System.Web.HttpPostedFileBase>)value;
        var firstfile = uploadedFiles.FirstOrDefault();

        if (firstfile != null)
        {
            foreach (var file in uploadedFiles)
            {
                int pos = Array.IndexOf(stringArray, file.ContentType.Substring(6));

                if (pos > -1)
                {
                    if (file.ContentLength > 5242880)
                    {
                        return new ValidationResult(String.Format("Billedet: {0} er for stort. (Max. tilladt billede-størrelse xxxxx)", file.FileName));
                    }
                }
                else
                {
                    return new ValidationResult(String.Format("Billedt: {0} har et forkert format. Tilladte formater er - GIF, JPG, PNG, JPEG", file.FileName));
                }
            }
        }
        return ValidationResult.Success; 
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule mvr = new ModelClientValidationRule();
        mvr.ErrorMessage = "Forkert format";
        mvr.ValidationType = "validImageUpload";
        return new[] { mvr };
    }
}

jQuery

$(document).ready(function () {
    jQuery.validator.addMethod('validImageUpload', function (value, element, params) {
        var currentDate = new Date();
        alert('Working indsi´side');
            return false;

    }, '');

    jQuery.validator.unobtrusive.adapters.add('validImageUpload', function (options) {
        options.rules['validImageUpload'] = {};
        options.messages['validImageUpload'] = options.message;
    });
});
Imran Khan
  • 39
  • 1
  • 4
  • You have generated you input manually and omitted all the `data-*` attributes necessary for client side validation. Use `@Html.TextBoxFor(m => m.FileUploader, new { type="file", multiple="multiple"})` –  Sep 13 '16 at 12:34
  • Thanks. How to close this question. – Imran Khan Sep 13 '16 at 16:36

1 Answers1

0

The reason you do not get any client side validation is because you have not added the appropriate data-val-* attributes in your html. Always use the strongly typed HtmlHelper methods to generate your html, in your case

@Html.TextBoxFor(m => m.FileUploader, new { type="file", multiple="multiple"})

Internally the method reads the metatdata from the validation attributes and adds the appropriate attributes to the html. When the page is first rendered, the jquery.validate.unobtrusive.js file reads the values of those attributes and adds the rules to jquery.valdate.js for client side validation.

However there are multiple other issues with you implementation. Your validating 2 separate things - the file size and the file type - so you need 2 separate attributes. And your attribute is inflexible because you have hard coded the valid values into the code (you would have to repeat all the code to apply it to another property where you only wanted to allow say .pdf files). Your also not returning any parameters in the GetClientValidationRules() method to indicate what file types (or file size) is valid. And the javascript functions should not be inside document.ready().

For an implementation of a FileTypeAttribute, refer FileExtension Validation using custom validation creates duplicate and invalid data-* attributes. And for an implementation of a FileSizeAttribute, refer Client-side File Upload Size Validation in ASP.NET MVC (note that that solution is for a single file and would need to be modified for uploading multiple files).

I also recommend your study The Complete Guide To Validation In ASP.NET MVC 3 - Part 2.

Community
  • 1
  • 1