Skip to content

Instantly share code, notes, and snippets.

@Justinnn07
Created October 11, 2022 15:56
Show Gist options
  • Save Justinnn07/e053e18f5fa062d26047ac55d528559e to your computer and use it in GitHub Desktop.
Save Justinnn07/e053e18f5fa062d26047ac55d528559e to your computer and use it in GitHub Desktop.
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
import { Formik } from "formik";
import * as EmailValidator from "email-validator"; // used when validating with a self-implemented approach
import * as Yup from "yup"; // used when validating with a pre-built solution
import DoneIcon from "@mui/icons-material/Done";
function App() {
const [count, setCount] = useState(0);
return (
<>
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 500);
}}
validate={(values) => {
let errors = {};
if (!values.email) {
errors.email = "Required";
} else if (!EmailValidator.validate(values.email)) {
errors.email = "Invalid email address.";
}
const passwordRegex = /(?=.*[0-9])/;
if (!values.password) {
errors.password = "Required";
} else if (values.password.length < 8) {
errors.password = "Password must be 1 to 8 characters long.";
} else if (!passwordRegex.test(values.password)) {
errors.password = "Invalid password. Must contain one number.";
}
return errors;
}}
>
{(props) => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
} = props;
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
placeholder="Enter your password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
<button type="submit">Login</button>
</form>
<div>
<h1>
Must be between 1 to 8:{" "}
{errors.password ? (
<DoneIcon
fontSize="large"
sx={{
fill:
errors.password !==
"Password must be 1 to 8 characters long."
? "green"
: "red",
}}
/>
) : (
<DoneIcon
fontSize="large"
sx={{
fill: "lightgray",
}}
/>
)}
</h1>
</div>
</>
);
}}
</Formik>
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment