question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

$.validator.addMethod is ignored when trying to add custom validation rules

See original GitHub issue

I am trying to add a new rule called filesize which inspects the size of the attached file.

If the file’s size if 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 validator.

$.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', lement.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 ( in bytes)

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

Am I doing something wrong here? How can I register the filesize method with $.validator?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
MikeAlhayekcommented, Sep 5, 2018

The issue was resolved. jQuery validator by default does not validate hidden inputs. I added ignore: ":hidden:not('.force-validaion')", to $.validator.setDefaults then I added the force-validation class to the hidden input.

0reactions
jeronecommented, Aug 14, 2019

For anyone interested; below adds the class val-force to force validation on hidden element and the class val-ignore to ignore some elements:

	/* Ignore validation on some elements. */
	var ignores = $.validator.defaults.ignore.replace(/(^|\b)(:hidden)($|\b)/gi, ':hidden:not(.val-force)').split(',');
	ignores.push('.val-ignore');
	$.validator.setDefaults({ ignore: ignores.join(',') });
Read more comments on GitHub >

github_iconTop Results From Across the Web

jQuery validation custom validator not fired even though ...
After looking around in the source code of the validator plugin I've figured out that the problem was caused by the following lines:...
Read more >
jQuery.validator.addMethod()
Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function ...
Read more >
Multiple step form with jQuery validation
By submitting the form validate will be called again to check visible fields and ignoring the valid first step. Add validation method. There...
Read more >
Model validation in ASP.NET Core MVC and Razor Pages
Validation attributes let you specify validation rules for model properties. ... To specify a custom error message, use the attribute.
Read more >
How the jQuery validate plugin works internally - Nadeem Khedr
Add custom validation rules. ... $.validator.addMethod( 'notnumbers', function (value, element) { return !/[0-9]*/.test(value) }, 'Please don't ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found