semantic-ui-react - 使用 Yup 进行语义 ui-react 表单验证
问题描述
我阅读了这个解决方案,但这并没有真正回答这个问题。我正在使用 formik 和语义 UI 反应。是否可以将 Yup 与语义 UI 反应一起使用?如果是的话,有人可以提供一个例子吗?
解决方案
是的,这是可能的,这是一种方法。将此代码粘贴到 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"));
推荐阅读
- c# - 使用 C# HttpClient 在两个请求之间保持 PHP 会话处于活动状态
- android - 尝试在空对象引用上调用虚拟方法 'void android.view.MotionEvent.setLocation(float, float)'
- variables - 具有两个条件读取变量的 For 循环
- python - 在 Pygame 中缩放图像/矩形
- python - 将文件转换为 pandas 数据框并逐行访问元素
- regex - 如何regex_replace找到的每个实例?
- javascript - base64到图像转换和使用php上传实时服务器
- ios - 如何使用cordova或ionic v1在iOS/iphone中将“返回”按钮自定义为“完成”
- plc - CODESYS 能否用于硬件 PLC 的开发(即非模拟)?
- c# - 文本可见性第二次无法正常工作