Search code examples
javascriptjqueryvalidationrequirejsunobtrusive

Why do I recieve both "$jQval is undefined" and "$.validator.unobtrusive is undefined" when using RequireJS?


This has had me puzzled for a few hours now. When the script is in a non-requirejs javascript file it works fine. When I use it with RequireJS it fails to work and gives me the error messages in the question title (though the firebug console).

I was just trying to get it to "work" with RequireJS before attempting to refactor into a module.

The Html is rendering correctly. The scripts are loading correctly. Also, I'm using the require-jquery.js bundle download, which is referenced in the layout template across all pages.

main.js:

require.config({
   paths: {
       "maximum-filesize": "modules/validation/maximum-filesize"
   }
});

require(["maximum-filesize", "domReady!"], function (maxFileSize) {
});

maximum-filesize.js

require.config({
paths: {
    "jquery-validate": "libs/jquery/jquery.validate",
    "jquery-validate-unobtrusive": "libs/jquery/jquery.validate.unobtrusive"
    }
});

define(["jquery", "jquery-validate", "jquery-validate-unobtrusive", "domReady!"], function ($) {

    $.validator.unobtrusive.adapters.add(
        'filesize', ['maxsize'], function(options) {
            options.rules['filesize'] = options.params;

            if (options.messages) {
                options.messages['filesize'] = options.message;
            }
        });

        $.validator.addMethod('filesize', function (value, element, params) {
        if (element.files.length < 1) {
            // No files selected
            return true;
        }

        if (!element.files || !element.files[0].size) {
            // This browser doesn't support the HTML5 API
            return true;
        }

        return element.files[0].size < params.maxsize;
        }, '');
});

Edit 1

I just tried commenting out all of the above code, and replaced it with a simple:

 $('#Name').val("Hello");

This rendered "Hello" correctly in the #Name textbox, so JQuery is working.


Solution

  • You should use requires shim option to tell requires to load jquery before jquery validate. Otherwise load order is undefined.

    Another possible problem is calling requirejs.config 2 times. Requirejs has problems with merging configs