$.validator.addMethod is ignored when trying to add custom validation rules
See original GitHub issueI 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:
- Created 5 years ago
- Comments:11 (6 by maintainers)
Top GitHub Comments
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 theforce-validation
class to the hidden input.For anyone interested; below adds the class
val-force
to force validation on hidden element and the classval-ignore
to ignore some elements: