Forms

NextUI provides form components with built-in validation and styling to help users input and submit data effectively.

Labels and help text

Accessible forms start with clear, descriptive labels for each field. All NextUI form components support labeling using the Label component, which is automatically associated with the field via the id and for attributes on your behalf.

In addition, NextUI components support help text, which associates additional context with a field such as a description or error message. The label and help text are announced by assistive technology such as screen readers when the user focuses the field.

import {Input} from "@nextui-org/react";
<Input type="password" label="Password" description="Password must be at least 8 characters." />;

Most fields should have a visible label. In rare exceptions, the aria-label or aria-labelledby attribute must be provided instead to identify the element to screen readers.

Submitting data

How you submit form data depends on your framework, application, and server. By default,HTML forms are submitted via a full-page refresh in the browser. You can call preventDefault in the onSubmit event to handle form data submission via an API.

Frameworks like Next.js, Remix, and React Router provide their own ways to handle form submission.

Uncontrolled forms

A simple way to get form data is to use the browser's FormData API during the onSubmit event. You can send this data to a backend API or convert it into a JavaScript object using Object.fromEntries. Each field should have a name prop to identify it, and the values will be serialized as strings by the browser.

import * as React from "react";
import {Button, Form, Input} from "@nextui-org/react";
function Example() {
const [submitted, setSubmitted] = React.useState(null);
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
// Prevent default browser page refresh.
e.preventDefault();
// Get form data as an object.
const data = Object.fromEntries(
new FormData(e.currentTarget)
);
// Submit data to your backend API.
setSubmitted(data);
};
return (
<Form onSubmit={onSubmit}>
<Input
isRequired
errorMessage="Please enter a valid email"
label="Email"
labelPlacement="outside"
name="email"
placeholder="Enter your email"
type="email"
/>
<Button type="submit">Submit</Button>
{submitted && (
<div className="text-small text-default-500">
You submitted:{' '}
<code>{JSON.stringify(submitted)}</code>
</div>
)}
</Form>
);
}

Controlled forms

NextUI form components are uncontrolled by default, but if you need to manage state in real-time, you can use the useState hook to make the component controlled.

import {Button, Form, Input} from "@nextui-org/react";
function Example() {
const [name, setName] = React.useState("");
const onSubmit = (e) => {
e.preventDefault();
// Submit data to your backend API.
alert(name);
};
return (
<Form onSubmit={onSubmit}>
<Input value={name} onValueChange={setName} />
<Button type="submit">Submit</Button>
</Form>
);
}

Validation

Form validation is crucial for ensuring that users enter the correct data. NextUI supports native HTML constraint validation and allows for custom validation and real-time validation.

Built-in validation

NextUI form components support native HTML validation attributes like isRequired and minLength. These constraints are checked by the browser when the user commits changes (e.g., onBlur) or submits the form. You can display validation errors with custom styles instead of the browser's default UI.

import {Button, Form, Input} from "@nextui-org/react";
<Form validationBehavior="native">
<Input name="email" type="email" isRequired />
<Button type="submit">Submit</Button>
</Form>;

To enable native validation, set validationBehavior="native". By default, validationBehavior="aria" is set, which only marks the field as required or invalid for assistive technologies, without preventing form submission. You can change the form defaults for your entire app using NextUI Provider.

Customizing error messages

By default, error messages are provided by the browser. You can customize these messages by providing a function to the errorMessage prop.

import {Button, Form, Input} from "@nextui-org/react";
<Form validationBehavior="native">
<Input
label="Number"
isRequired
min={0}
max={100}
errorMessage={(validationResult) => {
if (validationResult.validationDetails.rangeOverflow) {
return "Value is too high";
}
if (validationResult.validationDetails.rangeUnderflow) {
return "Value is too low";
}
if (validationResult.validationDetails.valueMissing) {
return "Value is required";
}
}}
/>
<Button type="submit">Submit</Button>
</Form>;

Note: The default error messages are localized by the browser based on the browser/operating system language settings. The locale setting in NextUI Provider does not affect validation errors.

Custom validation

In addition to built-in constraints, you can provide a function to the validate prop to support custom validation.

import {Button, Form, Input} from "@nextui-org/react";
<Form>
<Input
label="Number"
type="number"
validate={(value) => {
if (value < 0 || value > 100) {
return "Value must be between 0 and 100";
}
}}
/>
<Button type="submit">Submit</Button>
</Form>;

Realtime validation

If you want to display validation errors while the user is typing, you can control the field value and use the isInvalid prop along with the errorMessage prop.

import {Input} from "@nextui-org/react";
export function Example() {
const [password, setPassword] = React.useState("");
const errors: string[] = [];
if (password.length < 8) {
errors.push("Password must be 8 characters or more.");
}
if ((password.match(/[A-Z]/g) ?? []).length < 2) {
errors.push("Password must include at least 2 upper case letters");
}
if ((password.match(/[^a-z]/gi) ?? []).length < 2) {
errors.push("Password must include at least 2 symbols.");
}
return (
<Input
label="Name"
value={password}
onValueChange={setPassword}
isInvalid={errors.length > 0}
errorMessage={() => (
<ul>
{errors.map((error, i) => (
<li key={i}>{error}</li>
))}
</ul>
)}
/>
);
}

Server validation

Client-side validation provides immediate feedback, but you should also validate data on the server to ensure accuracy and security. NextUI allows you to display server-side validation errors by using the validationErrors prop in the Form component. This prop should be an object where each key is the field name and the value is the error message.

import {Button, Form, Input} from "@nextui-org/react";
function Example() {
const [errors, setErrors] = React.useState({});
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
const result = await callServer(data);
setErrors(result.errors);
};
return (
<Form validationErrors={errors} onSubmit={onSubmit}>
<Input label="Username" name="username" />
<Input label="Password" name="password" type="password" />
<Button type="submit">Submit</Button>
</Form>
);
}
// Fake server used in this example.
function callServer(data) {
return {
errors: {
username: "Sorry, this username is taken.",
},
};
}

Schema validation

NextUI supports errors from schema validation libraries like Zod. You can use Zod's flatten method to get error messages for each field and return them as part of the server response.

// In your server.
import {z} from "zod";
const schema = z.object({
name: z.string().min(1),
age: z.coerce.number().positive(),
});
function handleRequest(formData: FormData) {
const result = schema.safeParse(Object.fromEntries(formData));
if (!result.success) {
return {
errors: result.error.flatten().fieldErrors,
};
}
return {
errors: {},
};
}

React Server Actions

Server Actions that allows seamless form submission to the server and retrieval of results. The useActionState hook can be used to get the result of server actions (such as errors) after submitting a form.

// app/add-form.tsx
"use client";
import {useActionState} from "react";
import {Button, Input, Label} from "@nextui-org/react";
import {createTodo} from "@/app/actions";
export function AddForm() {
const [{errors}, formAction] = useActionState(createTodo, {
errors: {},
});
return (
<Form action={formAction} validationErrors={errors}>
<Input name="todo" label="Task" />
<Button type="submit">Add</Button>
</Form>
);
}
// app/actions.ts
"use server";
export async function createTodo(prevState: any, formData: FormData) {
try {
// Create the todo.
} catch (err) {
return {
errors: {
todo: "Invalid todo.",
},
};
}
}

Remix

Remix actions handle form submissions on the server. You can use the useSubmit hook to submit form data to the server and the useActionData hook to retrieve validation errors from the server.

// app/routes/signup.tsx
import type {ActionFunctionArgs} from "@remix-run/node";
import {useActionData, useSubmit} from "@remix-run/react";
import {Button, Form, Input} from "@nextui-org/react";
export default function SignupForm() {
const [errors, setErrors] = React.useState({});
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
const result = await callServer(data);
setErrors(result.errors);
};
return (
<Form validationErrors={errors} onSubmit={onSubmit}>
<Input label="Username" name="username" />
<Input label="Password" name="password" type="password" />
<Button type="submit">Submit</Button>
</Form>
);
}
export async function action({request}: ActionFunctionArgs) {
try {
// Validate data and perform action...
} catch (err) {
return {
errors: {
username: "Sorry, this username is taken.",
},
};
}
}

Form libraries

In most cases, the built-in validation features of NextUI are sufficient. However, if you're building more complex forms or integrating NextUI components into an existing form, you can use a form library like React Hook Form or Formik.

React Hook Form

You can integrate NextUI components using Controller. Controller allows you to manage field values and validation errors, and reflect the validation result in NextUI components.

import {Controller, useForm} from "react-hook-form";
import {Button, Input, Label} from "@nextui-org/react";
function App() {
const {handleSubmit, control} = useForm({
defaultValues: {
name: "",
},
});
const onSubmit = (data) => {
// Call your API here.
};
return (
<Form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="name"
render={({field: {name, value, onChange, onBlur, ref}, fieldState: {invalid, error}}) => (
<Input
ref={ref}
isRequired
errorMessage={error?.message}
isInvalid={invalid}
label="Name"
name={name}
value={value}
onBlur={onBlur}
onChange={onChange}
/>
)}
rules={{required: "Name is required."}}
/>
<Button type="submit">Submit</Button>
</Form>
);
}

For more information about forms in React Aria, visit the React Aria Forms Guide.