Laravel中引入node_modules的jquery-validation出现validate不是函数问题
jquery-validation working with require() but works with CDN? Let's break down why you're seeing the "validate is not a function" error even though you've installed and required the jquery-validation package:
The Core Issue
jQuery plugins like jquery-validation rely on jQuery being available in the global scope (i.e., window.jQuery or window.$) to register their methods (like .validate()) onto jQuery's prototype.
When you use a CDN:
The CDN-hosted jQuery script exposes
jQueryand$globally, so when the CDN-hostedjquery-validationloads, it immediately finds the global jQuery instance and attaches thevalidatemethod to it.
But when using require():
- If you don't explicitly expose jQuery to the global window, the
jquery-validationmodule can't find the jQuery instance to attach its methods to. Even if npm installed jQuery as a dependency ofjquery-validation, it's loaded as a local module, not a global variable. - Your current code doesn't include a line to require and expose jQuery globally—you're only requiring
jquery-validation, which isn't enough.
Fixes to Try
1. Explicitly Expose jQuery Globally Before Requiring jquery-validation
First, make sure jQuery is installed (it should be a dependency of jquery-validation, but double-check with npm install jquery --save if needed). Then update your code to:
// First, expose jQuery to the global window window.$ = window.jQuery = require('jquery'); // Now load jquery-validation—it will find the global jQuery window.jqueryvalidation = require('jquery-validation'); // Rest of your code... window.Vue = require('vue'); window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; Vue.component('error-message', require('./components/Flash_Error_Message.vue')); Vue.component('like', require('./components/Like.vue')); const app = new Vue({ el: '#app' }); $(function(){ $('#postForm').validate({ // ... your validation rules and callbacks }); })
2. Use Webpack's ProvidePlugin (If Using Webpack)
If your project uses Webpack, you can configure it to automatically provide jQuery globally to all modules, so you don't need to manually assign it to window:
Add this to your webpack.config.js:
const webpack = require('webpack'); module.exports = { // ... other configuration settings plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) ] };
With this setup, you can keep your original require('jquery-validation') line, as Webpack ensures jQuery is available globally for the plugin to use.
Why This Works
By making jQuery available globally before loading jquery-validation, the plugin can attach its validate method to jQuery.fn (the jQuery prototype), which makes .validate() available on all jQuery objects like $('#postForm').
内容的提问来源于stack exchange,提问作者Theodore

