How would you validate a React form without a library?
Keep values and an errors object in state. Write a validate function that returns errors from the values, run it on submit (and optionally on blur), call preventDefault, and submit only when the errors object is empty.
Explain it simply
Validation is the bank clerk checking your cheque before accepting it. In React the clerk is a plain function: it receives the form values and returns an object of messages like { email: "Enter a valid email" }.
On submit, call e.preventDefault() so the browser does not reload the page, run the validator, store the errors in state and render them under the fields. If the object is empty, send the data.
Validate on blur to show errors after the user leaves a field, not while they are still typing. Server-side validation is still required, because client checks can be bypassed.
Example
function validate({ email, password }) {
const errors = {};
if (!/^\S+@\S+\.\S+$/.test(email)) errors.email = "Enter a valid email";
if (password.length < 8) errors.password = "Use at least 8 characters";
return errors;
}
function Login() {
const [values, setValues] = useState({ email: "", password: "" });
const [errors, setErrors] = useState({});
function onSubmit(e) {
e.preventDefault();
const found = validate(values);
setErrors(found);
if (Object.keys(found).length === 0) console.log("send", values);
}
// inputs omitted
return <form onSubmit={onSubmit}>{errors.email && <p>{errors.email}</p>}</form>;
}What to say in the interview
"I store values and errors in state, compute errors with a pure validate function on submit and blur, prevent the default submit, and only call the API when there are no errors. The server must validate again. For complex forms I use React Hook Form with a schema library."
Common mistakes
- Trusting only client-side validation.