Number Field
The NumberField component is a reusable numeric input built with Tailwind CSS for styling and Formik for form logic and validation. It helps you easily capture and validate number values in your forms. Ideal for use cases like quantity inputs, pricing fields, or any numeric data entry. Simple to integrate and fully customizable.
Number Field preview
Form with Number Field
Please install everything that's required
1. Setup codes
Before add the NumberField, we need to add the TextField first, you can see in this link.
Create a new file components/common/forms/NumberField.tsx and add this code below
jsximport React from "react"; import TextField from "./TextField"; export default function NumberField({ id, name, label, maxLength, }: { id: string; name: string; label?: string; maxLength?: number; }) { return ( <> <TextField id={id} name={name} type="number" label={label} maxLength={maxLength} /> </> ); }
2. Usages
Because the NumberField component is built base on Formik, so we need to wrap the Formik and Form tags out site of NumberField component.
jsx"use client"; import { Form, Formik } from "formik"; ... <Formik initialValues={{ age: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Age is ${values.age}`)} > <Form> <NumberField id="age" name="age" label="User age" /> .... </Form> </Formik>
You can see the UI like this
Form with Number Field
You can see all the source code
jsx"use client"; import { Form, Formik } from "formik"; import React from "react"; import * as Yup from "yup"; import Button from "@/components/Button"; import NumberField from "@/components/Form/NumberField"; const validationSchema = Yup.object().shape({ age: Yup.number().required("Age is required").moreThan(0, "Age must be greater than 0"), }); const TestingForm = () => { 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 Number Field</p> <Formik initialValues={{ age: "" }} validationSchema={validationSchema} onSubmit={(values) => alert(`Age is ${values.age}`)} > <Form> <NumberField id="age" name="age" label="User age" /> <div className="mt-6"> <Button type="submit" className="w-full"> <span> Submit <span aria-hidden="true">→</span> </span> </Button> </div> </Form> </Formik> </div> ); }; export default TestingForm;
Learn more to using NumberField component in Signin, Signup forms on this link