Java Input Validation

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 244 of 306

Java input validation is the process of checking that data coming into your program has the right type, length, format and range before you use it. Form fields, URL parameters, JSON bodies, files and even environment variables all come from outside your code, so none of them can be trusted.

Good validation stops crashes, bad data in the database and many attacks, such as SQL injection, path traversal and cross-site scripting. This lesson builds Java input validation step by step, from simple null checks to a complete registration form validator, and connects to the ideas in Java Secure Coding.


Java Input Validation: Allowlist vs Denylist

There are two ways to decide what is acceptable. An allowlist describes exactly what good input looks like and rejects everything else. A denylist tries to list bad input, which almost always misses something.

ApproachRuleExampleStrength
AllowlistAccept only known-good inputUsername matches [a-z][a-z0-9_]{2,15}Strong: new attack strings are rejected automatically
DenylistReject known-bad inputBlock <script> and DROP TABLEWeak: easy to bypass with <SCRIPT>, encodings or new tricks

Note: Always prefer an allowlist. Use a denylist only as an extra layer, for example to block reserved usernames that otherwise match your allowlist.


Null, Blank and Length Checks

The simplest checks are often the most important. Reject null, strip surrounding spaces, reject empty values and limit the length. A length limit also protects your program from extremely large inputs.

import java.util.Objects;

public class BasicChecks {
    static String validateName(String name) {
        Objects.requireNonNull(name, "name must not be null");
        String trimmed = name.strip();
        if (trimmed.isEmpty()) {
            throw new IllegalArgumentException("name must not be blank");
        }
        if (trimmed.length() > 30) {
            throw new IllegalArgumentException("name must be at most 30 characters");
        }
        return trimmed;
    }

    public static void main(String[] args) {
        String[] inputs = {"  Asha  ", "   ", null, "A".repeat(31)};
        for (String input : inputs) {
            try {
                System.out.println("Valid: [" + validateName(input) + "]");
            } catch (NullPointerException | IllegalArgumentException e) {
                System.out.println("Invalid: " + e.getMessage());
            }
        }
    }
}

Output:

Valid: [Asha]
Invalid: name must not be blank
Invalid: name must not be null
Invalid: name must be at most 30 characters

How it works:

  • Objects.requireNonNull throws a NullPointerException with a clear message when the value is missing.
  • strip() removes leading and trailing whitespace, including Unicode spaces, so " Asha " becomes "Asha" and a value of only spaces becomes empty.
  • The length check runs on the stripped value and rejects anything over 30 characters.
  • The method returns the cleaned value, so the caller stores "Asha", not the raw input.

Validating Numbers and Ranges

Numbers from a form always arrive as text. Convert them with Integer.parseInt (or Long.parseLong, new BigDecimal(...) for money), catch NumberFormatException, and then check that the value is inside the allowed range.

public class NumberValidation {
    static int parseAge(String text) {
        int age;
        try {
            age = Integer.parseInt(text.strip());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("age must be a whole number: \"" + text + "\"");
        }
        if (age < 13 || age > 120) {
            throw new IllegalArgumentException("age must be between 13 and 120, got " + age);
        }
        return age;
    }

    public static void main(String[] args) {
        String[] inputs = {"25", " 42 ", "abc", "12.5", "-5", "99999999999", "130"};
        for (String input : inputs) {
            try {
                System.out.println("OK      " + parseAge(input));
            } catch (IllegalArgumentException e) {
                System.out.println("INVALID " + e.getMessage());
            }
        }
    }
}

Output:

OK      25
OK      42
INVALID age must be a whole number: "abc"
INVALID age must be a whole number: "12.5"
INVALID age must be between 13 and 120, got -5
INVALID age must be a whole number: "99999999999"
INVALID age must be between 13 and 120, got 130

How it works:

  • parseInt accepts only an optional sign and digits. "abc", "12.5" and "99999999999" (too large for int) all throw NumberFormatException, which the method turns into a clear message.
  • A successfully parsed number can still be wrong. The range check rejects -5 and 130.
  • The error messages tell the user what is expected, which is friendlier than a stack trace.

Regex Allowlist Validation in Java

A regular expression is the natural way to describe an allowlist for text with a fixed shape, such as usernames, postal codes and phone numbers. The Java Regular Expressions lesson covers the syntax in detail.

import java.util.regex.Pattern;

public class RegexAllowlist {
    // Compile once and reuse: Pattern objects are thread-safe
    private static final Pattern USERNAME = Pattern.compile("[a-z][a-z0-9_]{2,15}");
    private static final Pattern PIN_CODE = Pattern.compile("[1-9][0-9]{5}");     // Indian PIN code
    private static final Pattern PHONE = Pattern.compile("[6-9][0-9]{9}");        // Indian mobile number

    static void check(String label, Pattern pattern, String value) {
        boolean valid = pattern.matcher(value).matches();
        System.out.printf("%-8s %-22s %s%n", label, "\"" + value + "\"", valid ? "valid" : "INVALID");
    }

    public static void main(String[] args) {
        check("username", USERNAME, "asha_99");
        check("username", USERNAME, "Asha");
        check("username", USERNAME, "ab");
        check("username", USERNAME, "asha'; DROP TABLE");
        check("pincode", PIN_CODE, "600001");
        check("pincode", PIN_CODE, "060001");
        check("phone", PHONE, "9876543210");
        check("phone", PHONE, "98765 43210");
    }
}

Output:

username "asha_99"              valid
username "Asha"                 INVALID
username "ab"                   INVALID
username "asha'; DROP TABLE"    INVALID
pincode  "600001"               valid
pincode  "060001"               INVALID
phone    "9876543210"           valid
phone    "98765 43210"          INVALID

How it works:

  • matcher(value).matches() requires the whole string to match. With find() instead, "asha'; DROP TABLE" would be accepted because it contains a valid part, so always use matches() for validation.
  • [a-z][a-z0-9_]{2,15} means one lowercase letter followed by 2 to 15 lowercase letters, digits or underscores. "Asha" fails because of the capital letter, and "ab" is too short.
  • The PIN code pattern does not allow a leading zero, and the phone pattern requires exactly 10 digits starting with 6 to 9, so the version with a space fails.
  • The patterns are compiled once into static final fields. Compiling a pattern on every call wastes time.

Note: Keep patterns simple and bounded with {min,max}. Nested repetition such as (a+)+ can take exponential time on crafted input, which attackers use for denial-of-service (ReDoS).


Validating Enums and Dates

When a value must be one of a fixed set, convert it into an enum. When a value is a date, parse it into a LocalDate with a strict formatter. In both cases you replace an untrusted string with a typed value that cannot be invalid.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class TypedValidation {
    enum CourseLevel { BEGINNER, INTERMEDIATE, ADVANCED }

    static CourseLevel parseLevel(String text) {
        try {
            return CourseLevel.valueOf(text.strip().toUpperCase(Locale.ROOT));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("unknown level: " + text);
        }
    }

    // "uuuu" + STRICT rejects impossible dates such as 31 February
    private static final DateTimeFormatter DATE =
            DateTimeFormatter.ofPattern("dd-MM-uuuu").withResolverStyle(ResolverStyle.STRICT);

    static LocalDate parseStartDate(String text) {
        try {
            LocalDate date = LocalDate.parse(text, DATE);
            if (date.isBefore(LocalDate.of(2026, 1, 1))) {
                throw new IllegalArgumentException("start date must be in 2026 or later");
            }
            return date;
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("invalid date: " + text);
        }
    }

    public static void main(String[] args) {
        String[] levels = {"beginner", " Advanced ", "expert"};
        for (String level : levels) {
            try {
                System.out.println("Level OK: " + parseLevel(level));
            } catch (IllegalArgumentException e) {
                System.out.println("Level error: " + e.getMessage());
            }
        }
        String[] dates = {"15-06-2026", "31-02-2026", "2026-06-15", "10-10-2020"};
        for (String date : dates) {
            try {
                System.out.println("Date OK: " + parseStartDate(date));
            } catch (IllegalArgumentException e) {
                System.out.println("Date error: " + e.getMessage());
            }
        }
    }
}

Output:

Level OK: BEGINNER
Level OK: ADVANCED
Level error: unknown level: expert
Date OK: 2026-06-15
Date error: invalid date: 31-02-2026
Date error: invalid date: 2026-06-15
Date error: start date must be in 2026 or later

How it works:

  • CourseLevel.valueOf accepts only the exact constant names, so the input is stripped and upper-cased first. An unknown name throws IllegalArgumentException, which becomes a friendly error.
  • toUpperCase(Locale.ROOT) avoids locale surprises. In a Turkish locale, "i".toUpperCase() produces a dotted İ, which would not match BEGINNER.
  • The formatter uses uuuu with ResolverStyle.STRICT, so 31 February is rejected instead of being quietly changed to 28 February.
  • After parsing, a business rule rejects dates before 2026.

Normalizing Unicode Before Validation

Unicode has many characters that look like ASCII letters, such as the full-width admin. If you check reserved names before normalizing, these look-alikes slip through. Normalize first with java.text.Normalizer, then validate the normalized value.

import java.text.Normalizer;
import java.util.Locale;
import java.util.Set;

public class NormalizeInput {
    private static final Set<String> RESERVED = Set.of("admin", "root", "support");

    static String canonical(String input) {
        // NFKC turns look-alike "compatibility" characters into their plain forms
        String normalized = Normalizer.normalize(input, Normalizer.Form.NFKC);
        return normalized.strip().toLowerCase(Locale.ROOT);
    }

    public static void main(String[] args) {
        String[] requestedNames = {"admin", "Admin ", "admin", "asha"};
        for (String name : requestedNames) {
            boolean naiveBlocked = RESERVED.contains(name);
            boolean safeBlocked = RESERVED.contains(canonical(name));
            System.out.printf("%-8s naive check: %-7s normalized check: %s%n",
                    name.strip(), naiveBlocked ? "blocked" : "allowed", safeBlocked ? "blocked" : "allowed");
        }
    }
}

Output:

admin    naive check: blocked normalized check: blocked
Admin    naive check: allowed normalized check: blocked
admin    naive check: allowed normalized check: blocked
asha     naive check: allowed normalized check: allowed

How it works:

  • The third name is written with full-width letters a to n. It looks like admin, but RESERVED.contains does not find it.
  • Normalizer.Form.NFKC maps compatibility characters to their standard forms, so the full-width letters become plain admin.
  • After normalizing, stripping and lower-casing, every variant of admin is blocked.

Validation vs Output Encoding

Validation decides whether input is acceptable. Output encoding makes sure data is displayed safely in a specific place, such as HTML. A comment field must allow < and ', so you cannot validate them away; you encode them when you write the page.

public class HtmlEncoding {
    // Encode the five characters that have special meaning in HTML
    static String escapeHtml(String text) {
        StringBuilder safe = new StringBuilder(text.length());
        for (char c : text.toCharArray()) {
            switch (c) {
                case '<' -> safe.append("<");
                case '>' -> safe.append(">");
                case '&' -> safe.append("&");
                case '"' -> safe.append(""");
                case '\'' -> safe.append("'");
                default -> safe.append(c);
            }
        }
        return safe.toString();
    }

    public static void main(String[] args) {
        String comment = "Great lesson! <script>alert('hacked')</script>";
        System.out.println("Unsafe HTML: <p>" + comment + "</p>");
        System.out.println("Safe HTML:   <p>" + escapeHtml(comment) + "</p>");
    }
}

Output:

Unsafe HTML: <p>Great lesson! <script>alert('hacked')</script></p>
Safe HTML:   <p>Great lesson! <script>alert('hacked')</script></p>

How it works:

  • Printed directly into HTML, the comment would contain a working <script> tag. This is cross-site scripting (XSS).
  • escapeHtml replaces the five special HTML characters with entities, so the browser shows the text instead of running it.
  • The rule of thumb: validate on input, encode on output. For SQL the "encoding" is a PreparedStatement, and for HTML it is escaping, usually done for you by a template engine such as Thymeleaf.

Real-World Example: A Registration Form Validator

This validator checks a whole sign-up form. It turns raw strings into a typed, trusted Registration record, collects all errors at once so the user can fix everything in one go, and never echoes the password back.

import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;

public class RegistrationValidator {
    // Raw data exactly as it arrived from a web form (every field is a String)
    record RegistrationForm(String username, String email, String age, String course, String password) { }

    // Clean, typed data that the rest of the app can trust
    record Registration(String username, String email, int age, String course) { }

    record ValidationResult(Registration registration, List<String> errors) {
        boolean isValid() { return errors.isEmpty(); }
    }

    private static final Pattern USERNAME = Pattern.compile("[a-z][a-z0-9_]{2,15}");
    // A practical email check, not the full RFC 5322 grammar
    private static final Pattern EMAIL = Pattern.compile("[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}");
    private static final Set<String> COURSES = Set.of("java", "python", "go", "data-mining");
    private static final Set<String> RESERVED = Set.of("admin", "root", "support");

    static ValidationResult validate(RegistrationForm form) {
        List<String> errors = new ArrayList<>();

        // Username: normalize, then allowlist, then business rule
        String username = canonical(form.username());
        if (!USERNAME.matcher(username).matches()) {
            errors.add("username: 3-16 chars, lowercase letters, digits or _, starting with a letter");
        } else if (RESERVED.contains(username)) {
            errors.add("username: '" + username + "' is reserved");
        }

        // Email: length limit first, so the regex never runs on huge input
        String email = form.email() == null ? "" : form.email().strip();
        if (email.length() > 254 || !EMAIL.matcher(email).matches()) {
            errors.add("email: not a valid address");
        }

        // Age: parse to int, then range check
        int age = 0;
        try {
            age = Integer.parseInt(form.age() == null ? "" : form.age().strip());
            if (age < 13 || age > 120) {
                errors.add("age: must be between 13 and 120");
            }
        } catch (NumberFormatException e) {
            errors.add("age: must be a whole number");
        }

        // Course: must be one of a fixed set of values
        String course = canonical(form.course());
        if (!COURSES.contains(course)) {
            errors.add("course: choose one of " + COURSES.stream().sorted().toList());
        }

        // Password: only length rules here; it is hashed, never stored or echoed
        String password = form.password() == null ? "" : form.password();
        if (password.length() < 12 || password.length() > 128) {
            errors.add("password: must be 12-128 characters");
        }

        Registration clean = errors.isEmpty()
                ? new Registration(username, email.toLowerCase(Locale.ROOT), age, course)
                : null;
        return new ValidationResult(clean, List.copyOf(errors));
    }

    private static String canonical(String value) {
        if (value == null) return "";
        return Normalizer.normalize(value, Normalizer.Form.NFKC).strip().toLowerCase(Locale.ROOT);
    }

    public static void main(String[] args) {
        List<RegistrationForm> submissions = List.of(
            new RegistrationForm("Asha_99", "Asha@Example.com", "21", "Java", "Lotus-Chennai-2026"),
            new RegistrationForm("admin", "admin@gocourse", "abc", "hacking", "123"),
            new RegistrationForm("<script>", null, "7", "python", "x".repeat(200))
        );

        int formNumber = 1;
        for (RegistrationForm form : submissions) {
            ValidationResult result = validate(form);
            System.out.println("Form " + formNumber++ + ":");
            if (result.isValid()) {
                System.out.println("  ACCEPTED " + result.registration());
            } else {
                result.errors().forEach(error -> System.out.println("  - " + error));
            }
        }
    }
}

Output:

Form 1:
  ACCEPTED Registration[username=asha_99, email=asha@example.com, age=21, course=java]
Form 2:
  - username: 'admin' is reserved
  - email: not a valid address
  - age: must be a whole number
  - course: choose one of [data-mining, go, java, python]
  - password: must be 12-128 characters
Form 3:
  - username: 3-16 chars, lowercase letters, digits or _, starting with a letter
  - email: not a valid address
  - age: must be between 13 and 120
  - password: must be 12-128 characters

How it works:

  1. Two records, two levels of trust. RegistrationForm holds raw strings from the browser. Registration holds clean, typed values. Only a fully valid form produces a Registration, so the rest of the app never sees unchecked data.
  2. Collect every error. Each check adds a message to a list instead of throwing, so form 2 reports five problems in one response.
  3. Username. The value is normalized with NFKC, stripped and lower-cased, then checked against the allowlist and the reserved names. The full-width admin becomes admin and is rejected as reserved, while <script> fails the pattern.
  4. Email. The 254-character limit runs before the regex, which keeps the regex fast. admin@gocourse fails because it has no top-level domain, and a null email is treated as empty.
  5. Age and course. The age is parsed and range-checked, and the course must be in a fixed set. "Java" is accepted because it is normalized to java.
  6. Password. Only the length is checked, and the message never includes the password itself. A valid password would next be hashed as shown in Java Password Hashing.

Note: In Spring Boot and Jakarta EE applications, the same rules are usually written as Jakarta Bean Validation annotations such as @NotBlank, @Size, @Pattern, @Email and @Min. The ideas in this lesson are exactly what those annotations do for you.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Input Validation and get answers drawn from it.

Signed-in readers only.