Skip to content

Commit

Permalink
feat: use formik
Browse files Browse the repository at this point in the history
  • Loading branch information
laoriy committed Feb 21, 2024
1 parent 60bc681 commit 1110d4f
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 11 deletions.
3 changes: 2 additions & 1 deletion 5.react/formik/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
"web-vitals": "^2.1.4",
"yup": "^1.3.3"
},
"scripts": {
"start": "react-scripts start",
Expand Down
29 changes: 29 additions & 0 deletions 5.react/formik/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 51 additions & 10 deletions 5.react/formik/src/App.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,78 @@
import React from "react";
import { useFormik } from "formik";
import * as Yup from "yup";

const SignupForm = () => {
// Pass the useFormik() hook initial form values and a submit function that will
// be called when the form is submitted
const formik = useFormik({
initialValues: {
email: "",
username: "",
password: "",
},
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
console.log(values);
},
// validate: (values) => {
// const errors = {};
// if (!values.username) {
// errors.username = "请输入用户名";
// }
// if (values.username.length > 15) {
// errors.username = "用户名不能超过15位";
// }
// if (!values.password) {
// errors.password = "请输入密码";
// }
// if (values.password.length < 6) {
// errors.password = "密码不能少于6位";
// }
// return errors;
// },
validationSchema: Yup.object({
username: Yup.string()
.max(15, "用户名不能超过15位")
.required("请输入用户名"),
password: Yup.string().min(6, "密码不能少于6位").required("请输入密码"),
}),
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="email">Email Address</label>
<label htmlFor="username">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
id="username"
name="username"
type="text"
{...formik.getFieldProps("username")}
/>
<p>
{formik.touched.username && formik.errors.username
? formik.errors.username
: null}
</p>
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
{...formik.getFieldProps("password")}
/>

<p>
{formik.touched.password && formik.errors.password
? formik.errors.password
: null}
</p>

<button type="submit">Submit</button>
</form>
);
};
function App() {
return (
<h2>
<div>
<SignupForm />
</h2>
</div>
);
}

Expand Down

0 comments on commit 1110d4f

Please sign in to comment.