locked
custom multiple file upload client side annotation mvc 5 RRS feed

  • Question

  • User-1053470953 posted
    $(function () {
        jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
            // Set up test parameters
            var params = {
                fileextensions: options.params.fileextensions.split(',')
            };
    
            // Match parameters to the method to execute
            options.rules['fileextensions'] = params;
            if (options.message) {
                // If there is a message, set it for the rule
                options.messages['fileextensions'] = options.message;
            }
        });
    
        jQuery.validator.addMethod("fileextensions", function (value, element, param) {
            var extension = getFileExtension(value);
            var validExtension = $.inArray(extension, param.fileextensions) !== -1;
            return this.optional(element) || validExtension;
        });
    
        function getFileExtension(fileName) {
            var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
            if (extension != undefined) {
                return extension[0];
            }
            return extension;
        };
    }(jQuery));
    

    code just validate single file and ignore the rest of files

    I want to validate multiple files 

    Wednesday, January 20, 2016 6:51 AM

Answers

  • User-474980206 posted
    Because you set multiple, it's not enough to check the value passed to the validation method, you need to go to the file element, access the files list property and check the name of each file in the list.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2016 12:25 AM

All replies

  • User61956409 posted

    Hi Khedr,

    code just validate single file and ignore the rest of files

    I want to validate multiple files 

    It seems that you’d like to check the file extension, you could refer to the following code.

    <div>
        Select images:
        <input id="ffl" type="file" name="img" multiple onchange="myfunction()">
        <br />
        <ul></ul>
    </div>
    <script>
    function myfunction() {
        var files = $("#ffl").val();
        var silenames = files.split(",");
    
        var item = "";
        for (var i = 0; i < silenames.length; i++) {
            //alert(getFileExtension(silenames[i]));
            item += "<li>" + getFileExtension(silenames[i]) + "</li>";
        }
    
        $("ul").append(item);
    
    }
    
    function getFileExtension(fileName) {
        var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
        if (extension != undefined) {
            return extension[0];
        }
        return extension;
    };
    
    </script>
    

    Best Regards,

    Fei Han



    Thursday, January 21, 2016 5:34 AM
  • User-1053470953 posted
        public class FileUploadValidation : ValidationAttribute, IClientValidatable
        {
            private List<string> ValidExtensions { get; set; }
    
            public FileUploadValidation(string fileExtensions)
            {
                ValidExtensions = fileExtensions.Split('|').ToList();
            }
    
            public override bool IsValid(object value)
            {
                IList<HttpPostedFileBase> file = value as List<HttpPostedFileBase>;
                int fileCount = file.Count(f => f != null && f.ContentLength > 0);
                if (fileCount > 0)
                {
                    foreach (var item in file)
                    {
                        var fileName = item.FileName;
                        var isValidExtension = ValidExtensions.Any(y => fileName.EndsWith(y));
                        return isValidExtension;
                    }
                }
                return true;
            }
    
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientFileExtensionValidationRule(ErrorMessage, ValidExtensions);
                yield return rule;
            }
        }
    
        public class ModelClientFileExtensionValidationRule : ModelClientValidationRule
        {
            public ModelClientFileExtensionValidationRule(string errorMessage, List<string> fileExtensions)
            {
                ErrorMessage = errorMessage;
                ValidationType = "fileextensions";
                ValidationParameters.Add("fileextensions", string.Join(",", fileExtensions));
            }
        }
    [FileUploadValidation("docx|doc|rtf|pdf|txt", ErrorMessage = "required : docx/doc/rtf/pdf/txt")]
    public List<HttpPostedFileBase> UploadCV { get; set; }
    $(function () {
        jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
            var params = {
                fileextensions: options.params.fileextensions.split(',')
            };
    
            options.rules['fileextensions'] = params;
            if (options.message) {
                // If there is a message, set it for the rule
                options.messages['fileextensions'] = options.message;
            }
        });
    
        jQuery.validator.addMethod("fileextensions", function (value, element, param) {
            var extension = getFileExtension(value);
            var validExtension = $.inArray(extension, param.fileextensions) !== -1;
            return this.optional(element) || validExtension;
        });
    
        function getFileExtension(fileName) {
            var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
            if (extension != undefined) {
                return extension[0];
            }
            return extension;
        };
    }(jQuery));


    MVC validation server side and client side for input file multiple..

    when upload multiple file server side read multiple files side but client side not....

    why client side not read multiple files and validate!!!? 

    Thursday, January 21, 2016 9:48 AM
  • User-474980206 posted
    Because you set multiple, it's not enough to check the value passed to the validation method, you need to go to the file element, access the files list property and check the name of each file in the list.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2016 12:25 AM
  • User-1053470953 posted

    thank you bruce 

    Friday, January 22, 2016 7:29 PM