[React] Validate React Forms with Formik and Yup

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Validate React Forms with Formik and Yup相关的知识,希望对你有一定的参考价值。

Validating forms in React can take several lines of code to build. However, Formik‘s ErrorMessage component and Yup simplify that process.

 

import { ErrorMessage, Field, Form, Formik } from ‘formik‘;
import React from ‘react‘;
import { render } from ‘react-dom‘;
import ‘./index.css‘;
import ItemList from ‘./ItemList‘;
import * as Yup from ‘yup‘;

const initialValues = {
  item: ‘‘,
};

const validationSchema = Yup.object().shape({
  item: Yup.string().required(‘Item name is required‘),
});

const App = () => {
  const [items, setItems] = React.useState([]);

  return (
    <React.Fragment>
      <h2>Regular Maintenance:</h2>
      <ItemList items={items} />
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={values => {
          setItems([...items, values.item]);
        }}
      >
        <Form>
          <label htmlFor="item">Item:</label>
          <Field type="text" name="item" />
          <ErrorMessage name="item" />
          <button type="submit">Add Item</button>
        </Form>
      </Formik>
    </React.Fragment>
  );
};

export default App;

render(<App />, document.getElementById(‘root‘));

 

以上是关于[React] Validate React Forms with Formik and Yup的主要内容,如果未能解决你的问题,请参考以下文章

通过 React 发送令牌

React 模块解析失败:意外字符“@”

在 React 子组件上调用方法

react antd

React + FontAwesome + Bootstrap

使用带有钩子的 React.memo 来控制输入