9

I want to import 'jquery-validation' into an ES6 class

import $ from 'jquery'
import 'jquery-validation'

but when I do anywhere in the same file

$(...).validate({...})

I get the error

Uncaught TypeError: $(...).validate is not a function
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
philip_nunoo
  • 920
  • 3
  • 10
  • 21
  • What method did you use to make your `import` statement available on the browser? I have a gulp `browserify` task with `babelify` transform that works just fine ( I have the same import statements you wrote above). Check these references: https://github.com/babel/babelify, http://egorsmirnov.me/2015/05/25/browserify-babelify-and-es6.html – Gabriel Ferraz Dec 13 '16 at 15:13

2 Answers2

13

From the looks of your code example you weren't importing it correctly. Works for me with the following imports (with Webpack bundling):

import $ from 'jquery'
import validate from 'jquery-validation'
Brad Adams
  • 2,066
  • 4
  • 29
  • 38
0
import { useRef } from "react";
import $ from "jquery";
import validate from "jquery-validation";

import "./styles.css";

export default function App() {
  const ref = useRef();

  function handleFormSubmit(e) {
    e.preventDefault();

    $(ref.current).validate({
      rules: {
        name: { required: true },
        address: { required: true }
      },
      messages: {
        name: { required: "Name field is required" },
        address: { required: "Address field is required" }
      }
    });
  }

  return (
    <form ref={ref} onSubmit={handleFormSubmit} noValidate="novalidate">
      <input name="name" id="name" type="text" placeholder="Name" />
      <textarea
        name="address"
        id="address"
        cols="4"
        rows="4"
        placeholder="Address"
      ></textarea>
      <button type="submit">Submit</button>
    </form>
  );
}

And link https://codesandbox.io/s/gallant-dirac-7h8t6?file=/src/App.js:0-873

  • 2
    Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. Have a look here → [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Federico Baù Jan 25 '21 at 14:33