jquery validate not loaded requirejs

2019-07-09 04:14发布

I have a main module in RequireJS:

require([
    'jquery',
    'jquery.validate',
    'jquery.validate.unobtrusive'
], function ($) {
    $(document).ready(function () {
        var validator = $("form").validate();
        if ($("#txtFirstName").val() !== "")
            validator.element("#txtFirstName");
    });
});

When I load this page, I get a JavaScript error:

TypeError: $(...).validate is not a function var validator = $("form").validate();**

I don't now why? All scripts are loaded:

enter image description here

1条回答
贼婆χ
2楼-- · 2019-07-09 05:05

You'll need to configure shim to "wire" the dependencies correctly:

require.config({
  paths: {
    'jquery': 'path-to-jquery',
    'jquery.validate': 'path-to-jquery-validate',
    'jquery.validate.unobtrusive': 'path-to-jquery-validate-unobtrusive'
  },
  shim: {
    'jquery.validate': ['jquery'],
    'jquery.validate.unobtrusive': ['jquery', 'jquery.validate']
  }
});

require(['jquery', 'jquery.validate', 'jquery.validate.unobtrusive'], function ($) {
  // your code
});

More details (and examples) in the official documentation (look for the "For "modules" that are just jQuery or Backbone plugins..." section).

查看更多
登录 后发表回答