Monish Jerin
Monish Jerin

Reputation: 23

Validation message not showing react hooks using simple react validator

i am trying to validate a form, the validation seems to be working where as i am not able to show the message, in console shownmessage attribute is true when validation works, but its not displaying in UI, I tried different methods and i am new bie, just trying to learn the basics of react. So i am stuck now at showing validation error. check the below code of mine

import React, { useState, useRef } from "react";
import Header from "./Layouts/Header";
import Footer from "./Layouts/Footer";
import { PROJECT_NAME } from "./Config";
import SimpleReactValidator from "simple-react-validator";

const ContactUs = () => {
  document.title = PROJECT_NAME + " Contact Us";
  const [formData, SetFormData] = useState({
    cname: "",
    cemail: "",
    cmessage: "",
  });

  const [state, setState] = useState({
    cname: "",
  });

  const { cname, cemail, cmessage } = formData;

  const handleChange = (e) => {
    SetFormData({ ...formData, [e.target.name]: e.target.value });
    setState({
      cname: e.target.value,
    });
    //console.log(e.target);
  };

  const validator = new SimpleReactValidator({
    className: "text-danger",
    messages: {
      cname: "That is not an email.",
    },
    validators: {
      cname: {
        message: "The :attribute must be a valid IP address.",
      },
    },
  });

  const onSubmit = (e) => {
    e.preventDefault();
    const contactUsData = {
      cname: formData.cname,
      cmessage: formData.cmessage,
      cemail: formData.cemail,
    };
    console.log(validator);
    console.log(contactUsData);
    if (validator.allValid()) {
      alert("You submitted the form and stuff!");
    } else {
      validator.showMessages();
    }
  };

  return (
    <div>
      <Header />
      <div className="container" style={{ marginTop: "30px" }}>
        <div className="row">
          <h2>Contact US</h2>
          <div className="container">
            <form onSubmit={(e) => onSubmit(e)}>
              <div className="form-group">
                <label htmlFor="pwd">Name:</label>
                <input
                  type="text"
                  className="form-control"
                  id="pwd"
                  placeholder="Enter Name"
                  value={formData.cname}
                  name="cname"
                  onChange={handleChange}
                />
                {validator.message("cname", formData.cname, "required|alpha")}
              </div>
              <div className="form-group">
                <label htmlFor="email">Email:</label>
                <input
                  type="email"
                  className="form-control"
                  id="email"
                  placeholder="Enter email"
                  value={cemail}
                  name="cemail"
                  onChange={(e) => handleChange(e)}
                />
              </div>
              <div className="form-group">
                <label htmlFor="message">Message:</label>
                <textarea
                  className="form-control"
                  id="message"
                  placeholder="Enter Message"
                  value={cmessage}
                  name="cmessage"
                  onChange={(e) => handleChange(e)}
                ></textarea>
              </div>
              <button type="submit" className="btn btn-primary">
                Submit
              </button>
            </form>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};
export default ContactUs;

Upvotes: 0

Views: 1383

Answers (2)

xdlg
xdlg

Reputation: 11

OnSubmit doesn’t change any state, so the component won’t re-render. You will need to associate the validator with state so it can force a re-render and validator.message displays something.

I would probably get rid of your extra useState since it isn’t doing anything and store a “isValidated” flag in state (set by handleSubmit) to signal the validator to display messages on the next render. (Maybe clearing that state on handleChange).

Upvotes: 1

Bashtanov Prokhor
Bashtanov Prokhor

Reputation: 196

You should update component explicitly using something like this hook:

function useForceUpdate(){
    const [value, setValue] = useState(0);
    return () => setValue(value => value + 1);
}
  1. In your component add const forceUpdate = useForceUpdate();
  2. after validator.showMessages(); add forceUpdate();

Upvotes: 2

Related Questions