Java Record Compact Validation
Define immutable records with compact constructors for validation in Java applications.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.