简体   繁体   English

Formik 在 React 中不显示错误

[英]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.我尝试按照 Formik 官方网站上的教程进行操作,但无济于事。 I am using React-Bootstrap, Formik, and Yup for validation.我正在使用 React-Bootstrap、Formik 和 Yup 进行验证。 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 .似乎您的输入字段未连接到Formik You could use the Field from Formik to wire your inputs to Formik.您可以使用 Formik 中的Field将您的输入连接到 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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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