philip_nunoo
philip_nunoo

Reputation: 938

Import jQuery Validation

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

Upvotes: 9

Views: 10947

Answers (2)

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

Upvotes: 0

Brad Adams
Brad Adams

Reputation: 2069

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'

Upvotes: 13

Related Questions