使用Yup进行语义ui-react形式验证

时间:2018-06-12 19:32:59

标签: semantic-ui-react formik yup

我读过solution,但这并没有真正回答这个问题。我正在使用formik和semantic-ui-react。 是否可以使用具有语义-ui反应的Yup? 如果有人可以提供一个例子吗?

1 个答案:

答案 0 :(得分:3)

是有可能的,这是一种方法。将此代码粘贴到codesandbox.io中,并安装formik yup和semantic-ui-react之类的依赖项

import React from "react";
import { render } from "react-dom";
import { Formik, Field } from "formik";
import * as yup from "yup";
import { Button, Checkbox, Form } from "semantic-ui-react";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const App = () => (
  <>
    <Formik
      initialValues={{
        firstname: "",
        lastname: ""
      }}
      onSubmit={values => {
        alert(JSON.stringify(values));
      }}
      validationSchema={yup.object().shape({
        firstname: yup.string().required("This field is required"),
        lastname: yup.string().required()
      })}
      render={({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit
      }) => {
        return (
          <Form>
            <Form.Field>
              <label>First Name</label>
              <input
                placeholder="First Name"
                name="firstname"
                onChange={handleChange}
                onBlur={handleBlur}
              />
            </Form.Field>
            {touched.firstname && errors.firstname && (
              <div> {errors.firstname}</div>
            )}
            <Form.Field>
              <label>Last Name</label>
              <input
                placeholder="Last Name"
                name="lastname"
                onChange={handleChange}
                onBlur={handleBlur}
              />
            </Form.Field>
            {touched.lastname && errors.lastname && (
              <div> {errors.lastname}</div>
            )}
            <Form.Field>
              <Checkbox label="I agree to the Terms and Conditions" />
            </Form.Field>
            <Button type="submit" onClick={handleSubmit}>
              Submit
            </Button>
          </Form>
        );
      }}
    />
  </>
);

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