Validate String Minimum and Maximum Length in Java

Tags: String

In this Java core tutorial, we learn how to implement a method to validate a String with minimum and maximum length.

Implement utility class to validate String length

First step, we implement a new class named StringUtils with a method isValidLength() to check whether a String value is valid in minimum and maximum length or not.

StringUtils.java

public class StringUtils {
    public static boolean isValidLength(String value, int minLength, int maxLength) {
        if(value == null) {
            return false;
        }

        int length = value.length();
        return length >= minLength && length <= maxLength;
    }
}

Using isValidLength() method to check String values

In the following Java example program, we use the utility class above to validate different String values.

ValidateStringLengthExample.java

public class ValidateStringLengthExample {
    public static void main(String[] args) {
        // valid Strings
        System.out.println(StringUtils.isValidLength("test", 3, 10));
        System.out.println(StringUtils.isValidLength("test", 0, 4));
        System.out.println(StringUtils.isValidLength("", 0, 10));
        System.out.println(StringUtils.isValidLength("", 0, 0));

        // invalid Strings
        System.out.println(StringUtils.isValidLength("test", 0, 3));
        System.out.println(StringUtils.isValidLength("a", 2, 10));
        System.out.println(StringUtils.isValidLength("test", 0, 0));
        System.out.println(StringUtils.isValidLength(null, 0, 100));
    }
}
The output is:
true
true
true
true
false
false
false
false

Happy Coding 😊

Check a String Is a Valid Integer in Java

Validate Email Address in Java