Name field
In this tutorial, we will use Tailwind CSS and Formik to create the Name Field component. It will used a lot of in our forms like: Sign in form, sign up form, Contact us form, ...
1. Setup codes
Before add the NameField, we need to add the TextField first, you can see in this link.
Create a new file components/common/forms/NameField.tsx and add this code below
jsximport React from "react"; import * as Yup from "yup"; import TextField from "./TextField"; type NameFieldProps = { id?: string; name?: string; label?: string; }; export const nameFieldValidation = Yup.string() .required("Username Required") .min(3, "Username must be at least 3 characters") .max(20, "Username must not exceed 20 characters") .matches( /^[a-zA-Z0-9_ ]+$/, "Only letters, numbers, underscores and spaces are allowed", ); export default function NameField({ id, name, label }: NameFieldProps) { return ( <> <TextField id={id || "name"} name={name || "name"} label={label || "User name"} /> </> ); }
2. Usages
Because the NameField component is built base on Formik, so we need to wrap the Formik and Form tags out site of NameField component.
jsx"use client"; import { Form, Formik } from "formik"; ... <Formik initialValues={{ name: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Name is ${values.name}`)} > <Form className="flex flex-col gap-4"> <NameField /> ... </Form> </Formik>
You can see the UI
Form with Name Field
You can see the full source codes
jsx"use client"; import { Form, Formik } from "formik"; import React from "react"; import * as Yup from "yup"; import Button from "@/components/Button"; import NameField, { nameFieldValidation } from "@/components/Form/NameField"; const validationSchema = Yup.object().shape({ name: nameFieldValidation, }); 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 Name Field</p> <Formik initialValues={{ name: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Name is ${values.name}`)} > <Form className="flex flex-col gap-4"> <NameField /> <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 NumberField component in Signin, Signup forms on this link
You can get all my components in here -->