Java Record Compact Validation

Define immutable records with compact constructors for validation in Java applications.

JavaForm Validation

Code

javasnippet
9 lines
public record User(String email, int age, String role) {
    public User {
        if (!email.contains("@")) throw new IllegalArgumentException("invalid email");
        if (age < 0 || age > 150) throw new IllegalArgumentException("invalid age");
        if (!java.util.Set.of("admin", "user", "guest").contains(role))
            throw new IllegalArgumentException("invalid role");
        email = email.toLowerCase();
    }
}

How it works

Count the class User and the function User as the entire surface area of Java Record Compact Validation.

IllegalArgumentException is the guard’s signal — thrown at the branch, before any partial work happens.

Putting it to use

The main signature reads public record User(String email, int age, String role)

Core lines

if (!email.contains("@")) throw new IllegalArgumentException("invalid email");
if (age < 0 || age > 150) throw new IllegalArgumentException("invalid age");
throw new IllegalArgumentException("invalid role");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
Validation comes first — `IllegalArgumentException` marks the failure, before any partial work happens.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `User` at load time.