Client side validation for image width/height before upload, ASP.NET MVC5

879 views Asked by At

I am trying to validate width and height of image before upload. I created a validation attribute and server side works as expected, but i can not manage to fix the client side validation.

This is the custom validation attribute

public class ImageDimensionsAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly int _width;
        private readonly int _height;
        private readonly string _dims;

        public ImageDimensionsAttribute(int width, int height)
        {
            _width = width;
            _height = height;
            _dims = String.Format("{0},{1}", _width, _height);
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            var file = value as HttpPostedFileBase;

            using (var img = Image.FromStream(file.InputStream))
            {
                return img.Width <= _width && img.Height <= _height;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(Messages.InvalidImageDimensions, _width, _height);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "imagedimensions"
            };
            rule.ValidationParameters.Add("dims", _dims);
            yield return rule;
        }
    }

and my javascript

$(function () {
        $.validator.addMethod("imagedimensions", function (value, element, params) {
            if (value == null)
                return true;

            var file = element.files[0];           
            var reader = new FileReader();
            var image = new Image();
            var sizes = params.split(",");
            var maxWidth = parseInt(sizes[0]);
            var maxHeight = parseInt(sizes[1]);

            var result = false;
            reader.readAsDataURL(file);
            reader.onload = function (_file) {
                image.src = _file.target.result;                
                image.onload = function () {
                    var w = this.width,
                        h = this.height
                    console.log(w, h);
                    if (w > maxWidth || h > maxHeight) {
                        return false;
                    } else {                        
                        console.log("i am valid size but validator can not await");
                        return true;
                    }
                };                
            };
        });        

        $.validator.unobtrusive.adapters.addSingleVal("imagedimensions", "dims");
    }(jQuery));

Seems like javascript function does not await till reader.onload executes so it ALWAYS returns false - everything invalid. I am looking for a way to make javascript "await".

0

There are 0 answers