Formik Material UI Log In Form
import React, { useState } from "react";
import { Button, TextField, Box, Typography, Dialog } from "@mui/material";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
export function MaterialForm() {
const [openDialog, setOpenDialog] = useState(false);
// Password validation schema
const validationSchema = Yup.object({
email: Yup.string().email("Invalid Email").required("Please enter your email"),
password: Yup.string()
.min(8, "Password must be at least 8 characters")
.max(20, "Password must not exceed 20 characters")
.matches(/[a-z]/, "At least one lowercase letter required")
.matches(/[A-Z]/, "At least one uppercase letter required")
.matches(/[0-9]/, "At least one number required")
.matches(/[@$!%*?&]/, "At least one special character required")
.required("Please enter your password"),
});
return (
<Box sx={{ width: 500, mx: "auto", mt: 5, p: 3, border: "1px solid #ddd", borderRadius: 2 }}>
<Typography variant="h5" align="center" gutterBottom>
Login
</Typography>
<Formik
initialValues={{ email: "", password: "" }}
validationSchema={validationSchema}
onSubmit={(values) => alert(JSON.stringify(values, null, 2))}
>
{({ errors, touched, handleChange, handleSubmit }) => (
<Form onSubmit={handleSubmit}>
<TextField
fullWidth
label="Email"
name="email"
margin="normal"
onChange={handleChange}
error={touched.email && Boolean(errors.email)}
helperText={touched.email && errors.email}
/>
<TextField
fullWidth
label="Password"
name="password"
type="password"
margin="normal"
onChange={(e) => {
handleChange(e);
setOpenDialog(true); // Show password rules when typing
}}
error={touched.password && Boolean(errors.password)}
helperText={touched.password && errors.password}
/>
{/* Password Validation Rules Dialog */}
<Box sx={{ p: 2 }}>
<Typography>Password must contain:</Typography>
<ul>
<li>✅ At least 8 characters</li>
<li>✅ One uppercase letter (A-Z)</li>
<li>✅ One lowercase letter (a-z)</li>
<li>✅ One number (0-9)</li>
<li>✅ One special character (@$!%*?&)</li>
</ul>
</Box>
<Button type="submit" fullWidth variant="contained" sx={{ mt: 2 }}>
Log In
</Button>
</Form>
)}
</Formik>
</Box>
);
}
Comments
Post a Comment