Client-side validation checks form input in the browser before data is sent to a server. In an interview, place it in the submission sequence: the user submits, the browser checks values, then valid form data is collected, encoded, and sent. The server still performs its own validation. section 2.4
Two ways to perform the browser-side check are:
- Use built-in HTML validation attributes, such as `required` and `pattern`. section 2.4
- Use JavaScript or TypeScript logic for custom checks and error messages. section 2.4
A React form with custom checks
A form action reads `name` and `email` from `FormData`, runs `validateName` and `validateEmail`, and returns an error with the entered fields if either check fails. The request is attempted only after those checks. To explain the design, distinguish immediate browser feedback from the server’s separate integrity check. section 2.4
Listing 2.9 Advanced form implementation
const Form: React.FC = () => {
const [state, formAction, isPending] = useActionState<FormState, FormData>(
async (prevState, formData: FormData) => {
const name = formData.get('name') as string; #A
const email = formData.get('email') as string; #B
const nameError = validateName(name); #C
if (nameError) { #D
return {
data: null,
error: nameError,
fields: {
name,
email,
},
};
}
const emailError = validateEmail(email); #E
if (emailError) {
return {
data: null,
error: emailError,
fields: {
name,
email,
},
};
}
try {
...
return {
data,
error: null,
fields: {
name,
email,
},
};
} catch (error) {
return {
data: null,
error: `There was a problem with your submission: ${error}`,
fields: {
name,
email,
},
};
}
},
{
data: null,
error: null,
fields: {
name: '',
email: '',
},
}
);
return (
<form action={formAction}>
...
<label htmlFor="name">Name:</label>
<input type="text" name="name" defaultValue={state.fields!.name} /> #F
<label htmlFor="email">Email:</label>
<input type="email" name="email" defaultValue={state.fields!.email} /> #G
<input type="submit" value="Submit" disabled={isPending} />
{state.error && <div className="error">{state.error}</div>} #H
{state.data && (
<div className="success"> #I
Form submitted successfully: ${JSON.stringify(state.data)}
</div>
)}
...
</form>
);
}
The advanced form listing shows where custom validators run relative to the request and how invalid fields are retained for feedback. section 2.4







