Ratandeep Arunkumar
Ratandeep Arunkumar

Reputation: 65

Form validation using React hook form

I want to validate my forms before calling the onClick function. I have used react-hook-form component to implement the form-validation. However, it doesn't seem to work. Even when the form is empty if I click on the button an empty component will be created.

I'm a beginner to react. This project is a from a Udemy course and I wanted to make some improvements i.e form-validation.

import React, { useState } from "react";
import AddIcon from "@material-ui/icons/Add";
import Fab from "@material-ui/core/Fab";
import Zoom from "@material-ui/core/Zoom";
import { useForm } from "react-hook-form";

function CreateArea(props) {

  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  };

  const [createNote, setCreateNote] = useState({
    title: "",
    content: "",
  });

  const [isExpanded, setIsExpanded] = useState(false);

  
  function updateChange(event) {
    const { name, value } = event.target;
    setCreateNote((prevNote) => {
      return {
        ...prevNote,
        [name]: value,
      };
    });
  }

  function submitNote(event) {
    props.onAdd(createNote);
    setCreateNote({
      title: "",
      content: "",
    });
    event.preventDefault();
  }

  function expand(){
    setIsExpanded(true);
  }

  return (
    
    <div>
      <form onSubmit={handleSubmit(onSubmit)} className="create-note" >
        {isExpanded && <input
          onChange={updateChange}
          value={createNote.title}
          name="title"
          placeholder="Title"
          ref={register({ required: true ,maxLength: 15 })}
        />}
        {errors.title && <p>Title is required</p>}

        <textarea
          onClick={expand}
          onChange={updateChange}
          value={createNote.content}
          name="content"
          placeholder="Take a note..."
          rows={isExpanded ? "3" : "1"}
          ref={register({ required: true })}
        />
        {errors.content && <p>Content is required</p>}
        
        <Zoom in={isExpanded}>
          <Fab type="submit" onClick={submitNote}>
            <AddIcon />
          </Fab>
        </Zoom>

      </form>
    </div>
  );
}

export default CreateArea;

Upvotes: 0

Views: 8118

Answers (1)

doxxy
doxxy

Reputation: 41

I'm not really sure if I understand the question completely, but if you want to validate the form in the expand function, and act on whether it's valid or not, react-hook-form has a triggerValidation function that returns a promise for this purpose.

const { triggerValidation } = useForm();

function expand() {
    triggerValidation().then(valid => {
        if (valid) {
            setIsExpanded(true);
        }
    });
}

Upvotes: 1

Related Questions