Java Record Compact Validation

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

JavaForm Validation

Code

snippet
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();
    }
}