Form validation checks entered values as part of submission. In an interview, explain both where checks occur and what happens when a value fails: the browser can check inputs before collecting and sending form data, while the server validates received data before processing it. section 2.4
A practical validation answer should distinguish these responsibilities:
- Use built-in HTML attributes such as required and pattern, or JavaScript or TypeScript logic, for client-side checks. section 2.4
- Validate received data on the server for integrity and authenticity; client-side checks are not the end of the submission process. section 2.4
- Make errors understandable and accessible. An input can point to its error element with aria-describedby, while that element uses role="alert" and aria-live="assertive". section 2.4
Validate before submitting a React form
A form action reads name and email from FormData, runs validateName and validateEmail, and returns an error with the entered field values when either check fails. If both pass, it proceeds with the request. This makes the interview follow-up concrete: describe how the user sees an error without losing what they entered, then explain why the server still validates the request. 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 the order of field checks and the error state returned with retained values. section 2.4











































