Junior
Junior

Reputation: 12002

How to validate the file's size with jquery-validation-unobtrusive in ASP.NET MVC 5 project?

I have a web project that is written using c# on the top of ASP.NET MVC 5 framework. I am using jquery-validation-unobtrusive package to establish a client-side validation. I am trying to add a new rule called filesize which inspects the size of the attached file.

So when the attached file's size is greater than the allowed, I want to show client size error message.

I created FileSizeAttribute attribute to be able to use in my view-models to decorate my HttpPostedFileBase properties with to set the max allowed size. The CreatePerson class show how I am consuming it.

Then in my javascript files, I added the following code to register a new method called filesize in the jquery-validator.

Model

[Required, FileSize(4000), AcceptedFileExtension("jpg|pdf|csv|text")]
public HttpPostedFileBase Picture { get; set; }

View

<div class="form-group" id="Picture_Block">
    <label class="control-label col-md-2" for="Picture">Picture</label>
    <div class="col-md-10">
        <div class="input-group uploaded-file-group max-input-width">
            <label class="input-group-btn">
                <span class="btn btn-default">
                    Browse 
                    @Html.HiddenFor(x => x.Picture, new { @class= "hidden force-validaion", type = "file" })
                </span>
            </label>
            <input class="form-control uploaded-file-name" readonly="" type="text">
        </div>
        @Html.ValidationMessageFor(x => x.Picture)
    </div>
</div>

Validation scripts

$.validator.addMethod("filesize", function (value, element, param) {
    if (value === "") {
        return true;
    }
    var maxBytes = parseInt(param);
    if (element.files !== undefined && element.files[0] !== undefined && element.files[0].size !== undefined) {
        console.log('Dumping the file object', element.files[0]);
        var filesize = parseInt(element.files[0].size);
        return filesize <= maxBytes;
    }
    return true;
});

Then I added a new unobtrusive adapter called filesize to allow me to add the rule/message to the validation options like so

$.validator.unobtrusive.adapters.add('filesize', ['maxfilesize'], function (options) {
    // set the parameter
    options.rules['filesize'] = options.params.maxfilesize;
    if (options.message) {
        // If there is a message, set it for the rule
        options.messages['filesize'] = options.message;
    }
});

I can see the the adapter is being registered, but the method filesize is not being called.

I am expecting to show an error message when the user upload exceeds the set file-size however it is not being called when the file is attached.

I create a repository to show how the $.validator.addMethod("filesize", function (value, element, param) is not being called which can be download from MvcWithUnobtrusive

What I am doing wrong here? How can I register the filesize method with $.validator?

Upvotes: 1

Views: 1780

Answers (1)

user3559349
user3559349

Reputation:

Your file input for Picture is hidden, and by default, hidden inputs are not validated.

Your can override the default by including the following script

$.validator.setDefaults({ 
    ignore: [] 
});

or if you have other hidden elements that you don't want validated, then you could give the element a class name (say class="fileinput") and use

$.validator.setDefaults({ 
    ignore: ":hidden:not('.fileinput')"
});

Upvotes: 1

Related Questions