Alex T
Alex T

Reputation: 3754

React final form with datepicker validation

Is there any way to display error message if the validation on the Field level fails when using react datepicker?

I am using datepicker with react final form:

const DatePickerAdapter = ({ input: { onChange, value }, ...rest }) => (
  <DatePicker
    selected={value}
    onChange={(date) => {
      console.log(date);
      onChange(date);
    }}
    {...rest}
  />
);

And then I put into Field component from RFF:

      <Field
        name="date"
        validate={required}
        dateFormat="yyyy/MM/dd"
        component={DatePickerAdapter}
      />

The issue is that it wont display any error if for example I leave the field empty or any part of validation is not passing. Is there a way to display this error message somehow in final form component? Here is my codesandbox- other fields with validation can show error message but Field with datepicker is not: https://codesandbox.io/s/react-final-form-third-party-components-example-datepicker-forked-wzrqgr?file=/index.js:2392-2579

Upvotes: 1

Views: 703

Answers (2)

Alex
Alex

Reputation: 161

something like that:

const DatePickerAdapter = ({ input: { onChange, value }, meta, ...rest }) => (
  <>
    <DatePicker
      onChange={onChange}
      selected={value}
      slotProps={{ textField: { error: !!meta.error } }}
      {...rest}
    />
    {meta.error}
  </>
);

Upvotes: 0

Glen Bowler
Glen Bowler

Reputation: 13

my recommendation would be to use Formik and Yup. With Formik package use useFormik that will ask for initial values that would be empty string, validationSchema that would be from yup and lastly ask for onSubmit that is linked to button.

See a quick example in this url:

https://stackblitz.com/edit/react-ff8inu?file=src/App.js

This code will not work since the program is wrote inside Stackblitz react and not react native but idea stay the same

Upvotes: 1

Related Questions