One validation rule, two places: forms in React and Spring
Every form needs its rules twice. The browser needs them so people get instant feedback. The server needs them because anybody can send a request without using your form at all. So the same rule exists in two languages, and the question is how to stop them from drifting apart.
Here's how the contact form on this site handles it, including the parts that are less tidy than I'd like.
The server is the authority
The rule that matters is that client validation is a convenience and server validation is the actual control. Anything else on the client side is a hint.
On the server the request is a Java record with Bean Validation annotations:
public record ContactRequest(
@NotBlank(message = "This field is required")
@Size(max = 100, message = "Use at most 100 characters")
String name,
@NotBlank(message = "This field is required")
@Size(max = 254, message = "Enter a valid email address")
@Email(regexp = "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$", message = "Enter a valid email address")
String email,
@NotBlank(message = "This field is required")
@Size(min = 10, max = 5000, message = "Use between 10 and 5000 characters")
String message) {
}
The browser has the same rules in Zod, used through React Hook Form:
// Same rules as the server (ContactRequest.java). The server is authoritative; this is for quick feedback.
const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const schema = z.object({
name: z.string().trim().min(1, REQUIRED).max(100, 'Use at most 100 characters'),
email: z.string().trim().min(1, REQUIRED).max(254, INVALID_EMAIL).regex(EMAIL_PATTERN, INVALID_EMAIL),
message: z.string().trim().min(1, REQUIRED).min(10, 'Use at least 10 characters').max(5000, 'Use at most 5000 characters'),
});
The details that drift
Writing the two versions is easy. These are the differences that creep in later.
Trimming. A name of 100 characters plus a trailing space is valid or invalid depending on when you trim. Both sides here trim before checking. On the server, that happens in the record's compact constructor, so no code can ever see an untrimmed value:
public ContactRequest {
name = trim(name);
email = trim(email);
message = trim(message);
}
What "email" means. The default @Email in Hibernate Validator doesn't accept the same addresses as a browser's type="email" or Zod's .email(). If the client accepts something the server refuses, the user gets a confusing failure after submitting. Passing one explicit pattern to both sides avoids the disagreement. It's a deliberately loose pattern, too, because the only real proof of an email address is sending something to it.
String length. JavaScript and Java both count UTF-16 code units, so these agree. An emoji counts as two on each side. Python or a database column counting code points would not, so check that if another system is involved.
Phone numbers. Nobody should write this rule by hand. Google's libphonenumber is used on the server and its port, libphonenumber-js, in the browser. They come from one source but ship at different times, so very new number ranges can be accepted by one and refused by the other. That's the case where the server's answer simply has to win.
Errors must find their way back
Since the server can still refuse something the client accepted, its errors need to appear in the same place as the client's. The API returns one message per field:
{ "errors": { "email": "Enter a valid email address" } }
If a field breaks several rules, the server has to choose just one, consistently. An empty email is "required", not "invalid":
violations.stream()
.sorted(Comparator.comparing((ConstraintViolation<T> v) -> v.getPropertyPath().toString())
.thenComparing(v -> isRequired(v) ? 0 : 1)
.thenComparing(ConstraintViolation::getMessage))
.forEach(v -> errors.putIfAbsent(v.getPropertyPath().toString(), v.getMessage()));
The form then puts each message on its field using React Hook Form's setError, so a rule enforced only on the server looks exactly like one enforced in the browser.
Rules that need data belong only on the server. Whether a post exists, or whether a visitor has sent too many messages, can't be decided in the browser, and the same error path handles them.
Could one definition generate both?
Yes, partly. You can generate types and some constraints from an OpenAPI document, and Zod schemas can be generated from that. For a large API with many forms, I'd seriously consider it.
The catch is that generation handles simple constraints well and everything interesting badly: conditional rules, custom messages, and a phone rule that depends on the visitor's region. For one contact form, a generator would be more machinery than the rules it replaces.
What I do instead is cheaper. There's a comment at the top of the schema that names the Java class, so nobody can miss that the rules are paired. The server's tests pin the boundaries: exactly 100 characters passes and 101 fails. The browser's copy has no matching tests yet, and that's the weak spot in this setup. If someone changes a limit on one side only, nothing fails. The server still protects the data, but the form gives the wrong hint until somebody notices.
The practical rule
Put every rule on the server first. Copy to the client only those rules that make the form faster to fill in. Trim the same way, use the same patterns and word the messages identically, then test the boundaries on both sides. Two copies of a rule are fine as long as you know they're two copies.