Calvin Cheng
Calvin Cheng

Reputation: 36506

RequireJS and Making validate method available in js file

I have the following config.js

require.config({
  baseUrl: "/static/js",
  paths: {
    jquery: "src/jquery-1.7.2",
    jqueryui: "src/jquery-ui-1.10.0.custom/js/jquery-ui-custom", 
    angular: "src/angular/1.0.4/angular",
    bootstrap: "bootstrap/js/bootstrap"
  },
  shim: {
    "jquery-validation-1.10.0/dist/jquery.validation.min" : {
        deps: ["jquery"],
        exports: "jquery.validation"
    }
  }
});

In a js file that I am loading up (named signup.js), I am attempting to make the validate method from jquery validation plugin available.

# File signup.js

define(["jquery"], function($) {

$('#beta_signup_form button[type=submit]').attr("disabled", "disabled");

$('#beta_signup_form').validate({
    rules: {
        name: {
            required: true,
            minlength: 4
        },
        email: {
            required: true,
            email: true 
        }
    },
    focusCleanup: true,
    onkeyup: false,
    errorElement: "span",
      ... the rest of the code ...

I am getting an error in my console which says Uncaught TypeError: Object [object Object] has no method 'validate'.

How do I pass in the validate method to my signup.js script?

Upvotes: 1

Views: 1877

Answers (1)

Simon Smith
Simon Smith

Reputation: 8044

You'll need to tweak your config a little. Typically when shimming a module you need to give it a path as well:

require.config({
  baseUrl: "/static/js",
  paths: {
    jquery: "src/jquery-1.7.2",
    jqueryui: "src/jquery-ui-1.10.0.custom/js/jquery-ui-custom", 
    angular: "src/angular/1.0.4/angular",
    bootstrap: "bootstrap/js/bootstrap",
    // Give validate a path
    "jquery-validate": "jquery-validation-1.10.0/dist/jquery.validation.min" 
  },
  shim: {
    // Now shim it
    "jquery-validate": {
        deps: ["jquery"],
        exports: "jquery.validation"
    }
  }
});


// Define it as a dependency. If the plugin doesn't return a value
// (most just augment the jQuery.fn) then no need to pass an argument 
// to your callback.    
define(["jquery", "jquery-validate"], function($) {
    // module code
});

You can shorten the code further if the plugin doesn't export a value:

  shim: {
    "jquery-validate": ["jquery"]
  }

More examples in the official docs - http://requirejs.org/docs/api.html#config-shim

Upvotes: 2

Related Questions