Monday, 14 March 2022

Formik - Render ErrorMessage automatically

I have the following code which you can find here:

https://stackblitz.com/edit/react-d2fadr?file=src%2FApp.js

import { ErrorMessage, Field, Form, Formik } from 'formik';
import React from 'react';
import { Button } from 'react-bootstrap';
import * as Yup from 'yup';

let fieldName = 'hexColor';

const TextInput = ({ field, value, placeholder, handleChange }) => {
  value = (field && field.value) || value || '';
  placeholder = placeholder || '';
  return (
    <input
      type="text"
      placeholder={placeholder}
      onChange={(e) => handleChange(e.target.value)}
      value={value}
    />
  );
};

export default () => {
  const onSubmit = (values, { setSubmitting }) => {
    console.log(values);
    setSubmitting(false);
  };

  return (
    <Formik
      initialValues=
      validationSchema={Yup.object({
        hexColor: Yup.string().test(
          fieldName,
          'The Hex Color is Wrong.',
          (value) => {
            return /^[0-9a-f]{6}$/.test(value);
          }
        ),
      })}
      onSubmit={onSubmit}
      enableReinitialize
    >
      {(formik) => {
        const handleChange = (value) => {
          value = value.replace(/[^0-9a-f]/g, '');
          formik.setFieldValue(fieldName, value);
        };
        return (
          <Form>
            <div>
              <Field
                component={TextInput}
                name={fieldName}
                placeholder="Hex Color"
                handleChange={handleChange}
              />&nbsp;
              <ErrorMessage name={fieldName} />
            </div>
            <Button
              type="submit"
              disabled={!formik.isValid || formik.isSubmitting}
            >
              Submit
            </Button>
          </Form>
        );
      }}
    </Formik>
  );
};

I want to know if is it any way to render the ErrorMessage element automatically?

The error message should be shown somewhere around the input text.

If you know how, you can fork the StackBlitz above with your suggestion.

Thanks!



from Formik - Render ErrorMessage automatically

No comments:

Post a Comment