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

问题描述 投票:1回答:1

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

semantic-ui-react formik yup
1个回答
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"));
© www.soinside.com 2019 - 2024. All rights reserved.