Password field
In this tutorial, we will use Tailwind CSS and Formik to create the Password Field component. It will used a lot of in our forms like: Sign in form, sign up form, Contact us form, ...
1. Setup codes
Create a new file components/common/forms/PasswordField.tsx and add this code below
jsximport React from "react"; import * as Yup from "yup"; import TextField from "./TextField"; type PassWordFieldProps = { className?: string; }; export const passwordFieldValidation = Yup.string() .min(8, "Password must be at least 8 characters") .matches(/[A-Z]/, "Password must contain at least one uppercase letter") .matches(/[a-z]/, "Password must contain at least one lowercase letter") .matches(/\d/, "Password must contain at least one number") .matches(/[@$!%*?&]/, "Password must contain at least one special character") .required("Password is required"); export default function PasswordField({ className }: PassWordFieldProps) { return ( <> <TextField id="password" name="password" type="password" label="Password" className={className} /> </> ); }
2. Usages
Because the PasswordField component is built base on Formik, so we need to wrap the Formik and Form tags out site of PasswordField component.
jsx"use client"; import { Form, Formik } from "formik"; ... <Formik initialValues={{ password: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Password is ${values.password}`)} > <Form className="flex flex-col gap-4"> <PasswordField /> ... </Form> </Formik>
You can see the UI of PasswordField
Form with Password Field
You can see all the source code of the form
jsx"use client"; import { Form, Formik } from "formik"; import React from "react"; import * as Yup from "yup"; import Button from "@/components/Button"; import PasswordField, { passwordFieldValidation } from "@/components/Form/PasswordField"; const validationSchema = Yup.object().shape({ password: passwordFieldValidation, }); const TestForm = () => { return ( <div className="not-prose flex max-w-2xl flex-col gap-3 rounded-lg border-2 p-6"> <p className="mb-4 text-3xl font-bold">Form with Password Field</p> <Formik initialValues={{ password: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Password is ${values.password}`)} > <Form className="flex flex-col gap-4"> <PasswordField /> <div> <Button type="submit" className="w-full"> <span> Submit <span aria-hidden="true">→</span> </span> </Button> </div> </Form> </Formik> </div> ); }; export default TestForm;
Learn more to using PasswordField component in Signin, Signup forms on this link
You can get all my components in here -->