简体   繁体   中英

Formik not displaying errors in React

I am trying to get the validation errors to display on touch but for some reason they're not showing up. I've tried following the tutorial on the official Formik website, but to no avail. I am using React-Bootstrap, Formik, and Yup for validation. What am I doing wrong?

Imports:

import * as React from 'react';
import { Container, Row, Col, Form } from 'react-bootstrap';
import { Formik } from 'formik';
import * as yup from 'yup';

Validation Schema:

const validationSchema = yup.object({
  companyName: yup
    .string()
    .required('Company Name is required')
    .min(3, 'Minimum 3 characters allowed')
    .max(100, 'Maximum 100 characters allowed'),
});

Form:

<Formik
    validationSchema={validationSchema}
    initialValues={{
        companyName: '',
    }}
    onSubmit={() => {}}
>
    {({ errors, touched }) => (
        <Form autoComplete='off'>
            <Form.Group>
                <Form.Label>
                    Company Name <span className='text-danger'>(*)</span>
                </Form.Label>
                <Form.Control type='text' name='companyName' placeholder='Enter Company Name' />
                <Form.Control.Feedback type='invalid'>{errors.companyName}</Form.Control.Feedback>
            </Form.Group>
        </Form>
    )}
</Formik>

Seems like your input fields are not connected to the Formik . You could use the Field from Formik to wire your inputs to Formik.

import * as React from 'react';
import { Container, Row, Col, Form } from 'react-bootstrap';
import { Formik, Field } from 'formik';
import * as yup from 'yup';

const validationSchema = yup.object({
  companyName: yup
    .string()
    .required('Company Name is required')
    .min(3, 'Minimum 3 characters allowed')
    .max(100, 'Maximum 100 characters allowed'),
});

export default function App() {
  return (
    <Formik
    validationSchema={validationSchema}
    initialValues={{
        companyName: '',
    }}
    onSubmit={() => {}}
>
    {({ errors, touched }) => (
        <Form autoComplete='off'>
            <Form.Group>
                <Form.Label>
                    Company Name <span className='text-danger'>(*)</span>
                </Form.Label>
                <Field type='text' placeholder='Enter Company Name' name="companyName" />
                <Form.Control.Feedback type='invalid'>{errors.companyName}</Form.Control.Feedback>
            </Form.Group>
        </Form>
    )}
</Formik>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM