Elastic UI DatePicker with React Hook Form and Yup Schema Validation

1.1k views Asked by At

I am trying to integrate elastic ui datepicker with react hook form and Yup schema validation. I know that by default Yup date schema is looking for a regular js Date or a string that can be parsed as such whereas elastic ui datepicker accepts and outputs moments for its dates. Therefore, I have tried to add a transformer to the date schema to parse the value into a moment. When I try this, it never registers that I've selected anything for the date, and the transformer never gets run. Here is an example:

import React, { useState } from "react";
import styled from "styled-components";
import {
  EuiButton,
  EuiForm,
  EuiFormRow,
  EuiFieldText,
  EuiPage,
  EuiPageBody,
  EuiPageContent,
  EuiPageHeader,
  EuiTitle,
  EuiPageHeaderSection,
  EuiDatePicker,
} from "@elastic/eui";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import { addUser } from "./logic";

const Container = styled.div`
  text-align: initial;
`;

const momentSchema = yup.date().clone().transform(function (value, originalValue) {
    if (this.isType(value)) {
      return value;
    }

    value = moment(originalValue);
    return value.isValid() ? value.toDate() : new Date("");
});

export const FormsPage = () => {
  const schema = yup.object().shape({
    firstName: yup.string().required(),
    lastName: yup.string().required(),
    email: yup.string().email().required(),
    dob: momentSchema.required(),
  });
  const [dob, setDob] = useState();
  const { errors, handleSubmit, register } = useForm({
    resolver: yupResolver(schema),
  });
  const dispatch = useDispatch();
  const onDobChange = (date) => {
    setDob(date);
  };
  const onSubmit = (data) => {
    dispatch(addUser(data));
  };

  return (
    <Container>
      <EuiPage>
        <EuiPageBody>
          <EuiPageHeader>
            <EuiPageHeaderSection>
              <EuiTitle size="1">
                <h1>Forms</h1>
              </EuiTitle>
            </EuiPageHeaderSection>
          </EuiPageHeader>
          <EuiPageContent>
            <EuiForm
              component="form"
              onSubmit={handleSubmit(onSubmit)}
              noValidate
            >
              <EuiFormRow
                label="First Name"
                isInvalid={!!errors.firstName}
                error={errors.firstName?.message}
              >
                <EuiFieldText
                  name="firstName"
                  inputRef={register}
                  isInvalid={!!errors.firstName}
                />
              </EuiFormRow>
              <EuiFormRow
                label="Last Name"
                isInvalid={!!errors.lastName}
                error={errors.lastName?.message}
              >
                <EuiFieldText
                  name="lastName"
                  inputRef={register}
                  isInvalid={!!errors.lastName}
                />
              </EuiFormRow>
              <EuiFormRow
                label="Email"
                isInvalid={!!errors.email}
                error={errors.email?.message}
              >
                <EuiFieldText
                  name="email"
                  inputRef={register}
                  isInvalid={!!errors.email}
                />
              </EuiFormRow>
              <EuiFormRow
                label="Date of Birth"
                isInvalid={!!errors.dob}
                error={errors.dob?.message}
              >
                <EuiDatePicker
                  name="dob"
                  inputRef={register}
                  isInvalid={!!errors.dob}
                  selected={dob}
                  onChange={onDobChange}
                />
              </EuiFormRow>
              <EuiFormRow>
                <EuiButton type="submit" fill>
                  Submit
                </EuiButton>
              </EuiFormRow>
            </EuiForm>
          </EuiPageContent>
        </EuiPageBody>
      </EuiPage>
    </Container>
  );
};

And this is what happens: Date is Required

0

There are 0 answers