2

I want to validate react-datepicker using react-hook-form and when i try it, its not working for me, also the validation message will not display. It is possible to put ref inside the DatePicker?

This is the version of react-hook-form that I used.

"react-hook-form": "^6.15.8"

This is my code

import React from "react";
import { useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

function Account() {
    const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ mode: "all" });

const [birthdate, setBirthdate] = useState(null);

    return (
        <div className="flex flex-col mx-5 my-2 space-y-2">
                  <DatePicker
                    className="birthdate border-2 border-pink-300 placeholder-gray-500 rounded-2xl w-full h-12 p-5 outline-none"
                    type="birthdate"
                    name="birthdate"
                    placeholderText="Birthdate"
                    selected={birthdate}
                    dateFormat="yyyy-MM-dd"
                    onChange={(date) => {
                      setBirthdate(date);
                    }}
                    peekNextMonth
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    closeOnScroll={true}
                    disabledKeyboardNavigation
                    ref={register({
                      required: {
                        value: true,
                        message: "*Birthdate is required",
                      },
                    })}
                  />
                  {errors.birthdate && (
                    <p className="text-red-600 text-sm cursor-default">
                      {errors.birthdate.message}
                    </p>
                  )}
                </div>
    )
}

export default Account

For the CSS Im using tailwind CSS Framework.

tdmayk
  • 85
  • 1
  • 2
  • 8

4 Answers4

0

According to the react-hook library, you can register an input and set it as required with the register function:

 {...register("birthdate", {
     required: true
 })}

I tested it in a code sandbox, and at the date selection, there was an error regarding a variable access that was undefined. To go around that, there's a hidden input to hold the date value to allow the check on the form submit. Try deleting it and moving the register to the DatePicker component.

import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

function Account() {
  const inputRef = useRef();
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  const [birthdate, setBirthdate] = useState("");

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="flex flex-col mx-5 my-2 space-y-2">
        <DatePicker
          className="birthdate border-2 border-pink-300 placeholder-gray-500 rounded-2xl w-full h-12 p-5 outline-none"
          type="birthdate"
          name="birthdate"
          placeholderText="Birthdate"
          dateFormat="yyyy-MM-dd"
          selected={birthdate}
          onChange={(date) => setBirthdate(date)}
          peekNextMonth
          showMonthDropdown
          showYearDropdown
          dropdownMode="select"
          closeOnScroll={true}
          disabledKeyboardNavigation
        />
        <input
          ref={inputRef}
          value={birthdate}
          type="hidden"
          {...register("birthdate", {
            required: true
          })}
        />
        {errors.birthdate && (
          <p className="text-red-600 text-sm cursor-default">
            Birthdate is required
          </p>
        )}
      </div>
      <input type="submit" />
    </form>
  );
}

export default Account;
  • When I try it, the validation message works fine. But when I click the submit button, I can still see the validation message even if I have already input the selected date, then he will not proceed to the next step when I click the submit button. – tdmayk Oct 26 '21 at 18:16
0

I wrapped it in react-hook-form Controller then added a hidden Form.Control so that error message can be fed and display to Form.Control.Feedback.

Notice the openingDay, in my case I needed it to be dynamic name that's why I placed it in a variable. In most cases you can use the dot operator to access the errors property name that you supplied e.g. errors.yourControllerName.

<Controller
  name={openingDay}
  control={control}
  isInvalid={!!errors[openingDay]}
  rules={{ required: 'Opening time is required' }}
  render={({ field: { onChange, value } }) => {
    return (
      <DatePicker
        onChange={onChange}
        selected={value}
        placeholderText="Select Opening Time..."
        disabled={!enabled}
        className="form-control"
        timeIntervals={30}
        dateFormat="h:mm aa"
        showTimeSelect
        showTimeSelectOnly
      />
    );
  }}
/>
<Form.Control
  type="hidden"
  isInvalid={!!errors[openingDay]}
/>
<Form.Control.Feedback type="invalid">
  {errors[openingDay] && errors[openingDay].message}
</Form.Control.Feedback>
Redd.o
  • 147
  • 2
  • 5
0

Did you try using controllers? Here is an example based on how I have done it in the past

import React from "react";
import { useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

function Account() {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({ mode: "all" });

  return (
    <div className="flex flex-col mx-5 my-2 space-y-2">
      <Controller
        control={control}
        name="birthdate"
        render={({ field }) => (
          <DatePicker
            className="birthdate border-2 border-pink-300 placeholder-gray-500 rounded-2xl w-full h-12 p-5 outline-none"
            name="birthdate"
            placeholderText="Birthdate"
            selected={field.value}
            dateFormat="yyyy-MM-dd"
            onChange={field.onChange}
            peekNextMonth
            showMonthDropdown
            showYearDropdown
            dropdownMode="select"
            closeOnScroll={true}
            disabledKeyboardNavigation
          />
        )}
      />
        {errors.birthdate && (
            <p className="text-red-600 text-sm cursor-default">
            {errors.birthdate.message}
          </p>
        )}
    </div>
  )
}

export default Account

Here is the official docs link with the usage of Controller. I hope this solves your issue, let me know if you still have some doubts.

Aditya
  • 76
  • 1
  • 5
-1

react-hooks-form work properly try it!

       import React from 'react';
       import { useState,useEffect,useRef,useMemo,useCallback } from 'react';
       import DatePicker from "react-datepicker";
        
        const [startDate, setStartDate] = useState(new Date());
        const [endDate, setEndDate]     = useState(new Date());
        
        let submitdata = {startDate,endDate};

         const submitform = async() => {             
           await DataService.myapi({submitdata})
            .then(res => {
                  
                  let response = res.data;
              })
          }

    return (
     <>

      <DatePicker selected={startDate}  maxDate={new Date()} className="form-control" onChange={(date) => setStartDate(date)} />

      <DatePicker selected={endDate}  maxDate={new Date()} className="form-control"  onChange={(date) => setEndDate(date)} /> </>)
   
Mr. Daiya
  • 1
  • 1
  • 1