0

I'm using react-datetime with formik and Yup validations. Now the issue is when the user enters a invalid date in an invalid format then there is nothing to validate. I tried making the input field disabled or read-only when the users picks a date from the calender.

Since I was not able to do that, I added a validation using yup & I also added custom errors using useState and they doesn't seem to work.

My requirement is to validate the date in format of MM/YYYY and also restrict the user to enter any value in the input after picking the month and year from the calender. It would also work if we make the input value read-only in that case.

import React, { useEffect, useState } from "react";
import Datetime from "react-datetime";
import { Formik } from "formik";

const dateRegExp = /^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$/;

const SignInSchema = Yup.object().shape({
  year_issuance_oc: Yup.string().matches(dateRegExp, "Values can neither be negative nor decimal").required("This field is required"),
})

export default function Index(){
  const [issunaceDate, setIssunaceDate] = useState(new Date());
  const [issuanceDateTouched, setIssunaceDateTouched] = useState(false);



 const isValidDate = (current) => {
    const year = current.year();
    const month = current.month();
    return (
      year >= 1947 &&
      ((year == moment().year() && month <= moment().month()) ||
        year < moment().year())
    );
  };

   return (
         <Container>
          <Formik
            validationSchema={SignInSchema}
            onSubmit={console.log}
            initialValues={intialValues}}
                >
                {({
                    handleSubmit,
                    handleChange,
                    handleBlur,
                    values,
                    touched,
                    isValid,
                    errors,
                    setFieldValue,
                }) => (
               
          <Row>
            <Form.Group controlId="year_issuance_oc" as={Col}>
              <Form.Label className="required-field font-Montserrat">
                {getTranslatedText("Year of issuance of OC")}
              </Form.Label>
            <Col className="p-0">
              <Datetime
                dateFormat="MM/YYYY"
                isValidDate={isValidDate}
                timeFormat={false}
                selectedDate={issunaceDate}
                closeOnSelect={true}
                onClick={(e) => {
                  setIssunaceDateTouched(true);
                }}
                onChange={(date) => {
                  try {
                    let y = `${date.month() + 1}/${date.year()}`;
                    setIssunaceDate(y);
                    
                  } catch (err) {
                    let y = `${moment().month() + 1}/${moment().year()}`;
                    setIssunaceDate(y);
                  }
                }}
              />
            </Col>
            {issuanceDateTouched && !(issunaceDate) && <p> Required </p>} 
          </Form.Group>
    )
         </Container>
)}


Any help would be appreciated!

enter image description here

Mahijendra
  • 335
  • 5
  • 15
  • You can use formik & yup given an error you can show it like this. {formik.errors.issunaceDate && formik.touched.issunaceDate ? (
    { formik.errors.issunaceDate }
    ) : null}
    – sedhal Jun 01 '22 at 10:52
  • @sedhal it's throwing an error `ReferenceError: formik is not defined` or `ReferenceError:errors is not defined` – Mahijendra Jun 01 '22 at 11:53
  • Okay, you can direct access using errors object like this {errors.issunaceDate ? (
    { errors.issunaceDate }
    ) : null}
    – sedhal Jun 01 '22 at 12:23

0 Answers0