Form validation in a React application usually starts on the client. Required fields, email formats, minimum lengths, and simple business rules can be checked before a request is sent to the API. This gives users immediate feedback and avoids unnecessary network requests.
The problem starts when the server applies validation rules that the React application does not know about, or when the server rejects data for reasons that cannot be checked safely on the client.
For example, a registration form may check that an email address looks valid. The API may additionally check whether that email is already registered. A product form may validate the price on the client, while the server checks whether the current user is allowed to change that price.
A reliable form therefore needs two levels of validation:
User input
↓
Client-side validation
↓
API request
↓
Server-side validation
↓
Success or validation errors
↓
Update React form stateThe important part is not choosing between client and server validation. Both have different responsibilities, and the React application needs a clear way to handle errors from each side.
Client Validation and Server Validation Have Different Jobs
Client-side validation exists mainly to improve the user experience.
For example:
Email → required
Password → minimum 8 characters
Name → requiredThese checks can happen immediately while the user is filling out the form.
Server-side validation has a different responsibility. The server is the final authority because it controls the database, business rules, authorization, and data integrity.
A server might reject a request because:
- The email already exists.
- The requested product is no longer available.
- The user does not have permission.
- A value conflicts with another record.
- A business rule was violated.
- The submitted data changed between loading the form and submitting it.
Client validation should therefore improve usability, but it should never be treated as a security boundary.
A Simple React Form
Consider a basic form:
import { useState } from "react";
export default function UserForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
async function handleSubmit(
event: React.FormEvent<HTMLFormElement>
) {
event.preventDefault();
const response = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name,
email
})
});
if (response.ok) {
// Handle success
}
}
return (
<form onSubmit={handleSubmit}>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<input
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Create User</button>
</form>
);
}This works for a simple request, but there is no mechanism for displaying validation errors returned by the API.
That becomes a problem when the server responds with something like:
{
"errors": {
"email": [
"An account with this email already exists."
]
}
}The React form needs to understand that response and connect the error to the correct field.
Keep Field Errors Separate From General Errors
A useful form state usually needs more than the field values.
For example:
const [errors, setErrors] = useState<Record<string, string[]>>({});
const [formError, setFormError] = useState<string | null>(null);These two states represent different types of problems.
Field errors belong to a specific input:
email
↓
"Email is already registered."A general error applies to the whole operation:
"Unable to save the user. Please try again."Keeping these separate makes the UI easier to manage.
Map Server Validation Errors to Form Fields
The API should ideally return a predictable validation structure.
For example:
{
"errors": {
"name": [
"Name is required."
],
"email": [
"Email is already registered."
]
}
}React can store this response directly:
const body = await response.json();
if (!response.ok) {
setErrors(body.errors ?? {});
return;
}Then the email input can display its server-side error:
<input
value={email}
onChange={e => setEmail(e.target.value)}
/>
{errors.email?.map(error => (
<div key={error}>{error}</div>
))}The important design decision is that the API error key must match the field name used by the frontend.
If the API returns:
emailthe frontend should not have to guess whether it means:
emailAddress
Email
userEmailA consistent error contract reduces this kind of mapping logic.
ASP.NET Core Validation Responses
ASP.NET Core commonly uses structured validation responses for model validation.
For example, a request model might look like:
public sealed class CreateUserRequest
{
[Required]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
}If validation fails, the API can return a structured response containing field-level errors.
A React application should treat this response as data rather than relying on a particular server-rendered error message.
The frontend needs to know:
Which field failed?
What message should be displayed?
Is the error related to the whole form?This makes the frontend independent of how the server internally implements validation.
Do Not Duplicate Every Server Rule in React
It is tempting to copy every backend validation rule into the frontend.
For example:
Client:
Email must be unique.
Server:
Email must be unique.The client cannot reliably determine whether an email is unique without asking the server.
Even if the React application sends a request such as:
GET /api/users/check-emailthere is still a race condition.
Another user could register the same email immediately afterward.
The server must therefore enforce the rule when the actual operation occurs.
Client-side checks should focus on rules that can provide useful immediate feedback, while the server remains authoritative.
Avoid Using Server Validation as the Only Validation
The opposite approach also creates a poor user experience.
Suppose the user submits:
Name: empty
Email: invalid
Password: too shortand the application sends the request anyway.
The server may return all three errors, but the user has to wait for a network request before seeing obvious problems.
Client-side validation can catch simple issues immediately.
For example:
function validateForm() {
const errors: Record<string, string[]> = {};
if (!name.trim()) {
errors.name = ["Name is required."];
}
if (!email.trim()) {
errors.email = ["Email is required."];
} else if (!email.includes("@")) {
errors.email = ["Enter a valid email address."];
}
return errors;
}Then:
const clientErrors = validateForm();
if (Object.keys(clientErrors).length > 0) {
setErrors(clientErrors);
return;
}This prevents an unnecessary API request.
Clear Old Errors Before Submitting Again
One common bug occurs when an old server error remains visible after the user changes the input.
For example:
Email:
[email protected]
Error:
Email is already registered.The user changes the email to:
but the old message remains.
Clear stale errors when a new submission starts or when the relevant field changes.
For example:
function handleEmailChange(value: string) {
setEmail(value);
setErrors(current => ({
...current,
email: []
}));
}This does not mean the new value is valid. It only means that an error associated with the previous value should not remain visible indefinitely.
The server response from the next submission becomes the authoritative result.
Handle Multiple Errors for One Field
A field can have more than one validation error.
For example:
{
"errors": {
"password": [
"Password is required.",
"Password must contain at least 8 characters."
]
}
}The React UI should be able to display multiple messages when necessary:
{errors.password?.map((error, index) => (
<div key={`${error}-${index}`}>
{error}
</div>
))}Alternatively, the API contract can define that only one user-facing message is returned per field.
The important point is to decide on the contract deliberately rather than allowing different endpoints to return different structures.
Handle Non-Validation Errors Separately
Not every failed request is a validation error.
For example:
400 → Invalid request
401 → Authentication required
403 → Not authorized
404 → Resource not found
409 → Conflict
422 → Validation-related failure
429 → Too many requests
500 → Server errorThe React form should not display every HTTP failure as if it were a field validation error.
For example, a 500 response should not produce:
Email:
Server errorInstead, the form can display a general error:
if (response.status >= 500) {
setFormError(
"The server could not process your request. Please try again."
);
return;
}This distinction becomes especially important in production because users need to understand whether they should correct their input or retry the operation.
Use a Consistent API Error Contract
Large applications often have many forms and APIs.
If every endpoint returns errors differently, frontend code becomes difficult to maintain.
For example, one endpoint might return:
{
"errors": {
"email": ["Invalid email"]
}
}while another returns:
{
"validationErrors": [
{
"field": "email",
"message": "Invalid email"
}
]
}and another returns:
{
"message": "Email is invalid."
}The React application now needs endpoint-specific parsing logic.
A consistent error contract is much easier to maintain.
A useful structure might contain:
{
"errors": {
"email": [
"Email is already registered."
]
},
"message": "The form contains validation errors."
}The exact contract can vary, but it should be predictable across the application.
Use Field Names That Match the API Contract
Nested request models introduce another challenge.
Suppose the server receives:
{
"address": {
"city": ""
}
}The validation error might be associated with:
address.cityThe React form needs to understand this field path.
A consistent naming strategy helps.
For example:
name
email
address.city
address.postalCodeInstead of creating unrelated frontend names and manually translating every field, keep the client and server request models aligned where practical.
Be Careful With Validation During Editing
Validation timing matters.
If an error appears on every keystroke, the form can become frustrating.
For example, showing:
Password must contain at least 8 characters.while the user has typed the first character may be technically correct but not necessarily useful.
Common approaches include:
On change
On blur
On submitFor simple fields, validating on blur can work well.
For more complex forms, validating on submit and then showing errors as the user corrects fields often provides a better balance.
The right choice depends on the form and the type of validation.
Handle Race Conditions in Asynchronous Validation
Some forms perform asynchronous checks while the user types.
For example:
User enters email
↓
API checks availability
↓
User changes email
↓
Another API request startsNow the responses can arrive out of order.
Suppose the user enters:
and then quickly changes it to:
The response for the first request could arrive after the second request.
If the application blindly updates the form state, it could display the wrong validation result.
AbortController can help cancel obsolete requests:
const controller = new AbortController();
fetch("/api/users/check-email", {
method: "POST",
body: JSON.stringify({ email }),
signal: controller.signal
});In a real React implementation, the controller should be tied to the lifecycle of the asynchronous validation operation so that outdated requests can be cancelled or ignored.
Do Not Trust Client Validation for Security
React validation can be bypassed.
A user can call the API directly without using the React application.
For example, a malicious client can send:
POST /api/users
Content-Type: application/jsonwith arbitrary values.
Therefore:
Client validation → user experience
Server validation → correctness and security
Database constraints → final data integrityThese layers have different responsibilities.
Important rules such as uniqueness, authorization, ownership, and financial constraints should always be enforced on the server and, where appropriate, at the database level.
Testing Server Validation in React
Forms should be tested with both client-side and server-side failures.
Useful scenarios include:
| Scenario | Expected behavior |
|---|---|
| Required field empty | Client validation displays field error |
| Invalid email | Client validation displays error |
| Duplicate email | Server validation displays email error |
| Invalid business rule | Server error maps to correct field |
| Unauthorized request | General authorization handling |
| Server unavailable | General retry/error message |
| Multiple field errors | All relevant field errors displayed |
| Successful submission | Errors cleared and success handled |
Testing only the happy path leaves many of the most important form behaviors unverified.
Common Mistakes
Treating Every HTTP Error as a Validation Error
A server failure and an invalid email address are different problems. Handle them separately.
Duplicating Server Rules Everywhere
Client validation should not become a second copy of the entire business layer.
Keeping Stale Errors
Clear or replace old validation messages when the user changes the affected value.
Using Different Field Names
Inconsistent field names make server-error mapping unnecessarily complicated.
Ignoring Nested Fields
Nested request objects require predictable field paths so errors can be displayed correctly.
Trusting React Validation
Client-side validation can be bypassed. The server must validate every important rule.
Showing Technical Errors Directly
Database exceptions and internal server messages should not normally be displayed to users.
Best Practices
Keep client validation focused on immediate user feedback.
Keep server validation authoritative for business rules and data integrity.
Use a consistent validation error structure across APIs.
Map server errors directly to form fields where possible.
Keep field-level errors separate from general request errors.
Clear stale errors when users correct their input.
Handle HTTP failures according to their meaning instead of treating every failure as validation.
Use cancellation or stale-response protection for asynchronous validation.
Test both client-generated and server-generated validation failures.
Make the API error contract part of the application design rather than something added after the frontend is already built.
Summary
React forms work best when client and server validation have clearly defined responsibilities. Client validation gives users fast feedback, while server validation remains the authority for business rules and data integrity.
The key is to use a consistent error contract so server validation errors can be mapped directly back to React fields. This keeps forms predictable, easier to test, and easier to maintain as the application grows.

Join the conversation! Your thoughts help the community grow.