eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll learn the basics of Apache Commons Validator, a powerful library from Apache Commons. It simplifies data validation in Java applications. Firstly, we will understand its use cases. Next, we’ll cover how to set it up. Subsequently, we will learn to use its built-in validators and explore practical use cases like form validation and API input validation.

2. What Is Apache Commons Validator?

Apache Commons Validator is a Java library that validates input data against common constraints. In particular, it provides out-of-the-box support for various types of validation, including email, URL, and date validations. We use it to avoid reinventing validation logic and ensure consistency across our application.

2.1. Why Use a Validation Library?

Data validation is error-prone and tedious, moreover, this is especially true when dealing with complex constraints. Consequently, a dedicated validation library like Apache Commons Validator saves time by providing pre-built validators for common use cases. In addition, not only does it promote cleaner code, but it also ensures that inputs are consistently checked. In the long run, that improves the overall security and integrity of the applications.

2.2. Real-World Use Cases for Apache Commons Validator

APIs need robust validation to ensure they only accept correctly formatted data.  With this in mind, Apache Commons Validator allows us to validate input payloads quickly. Moreover, we don’t have to write custom validation logic from scratch. This is especially useful when clients send data over HTTP requests. In reality, in these scenarios, inputs like URLs, numeric values, credit card numbers, or postal codes require validation before further processing.

Validation also plays a critical role in ensuring the security and integrity of data within an application. Improperly validated data can lead to security vulnerabilities like SQL injection or cross-site scripting (XSS). We use it to reduce such risks by applying strict input validation rules. It is important to realize that it ensures only valid data is allowed into the system and safeguards against malicious entries.

3. Maven Dependencies

We need to add the commons-validator dependency to our Maven pom.xml:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.9.0</version>
</dependency>

4. Built-in Validators

The reusable validators are in the org.apache.commons.validator.routines package. Commons Validator serves two purposes: providing standard, independent validation routines/functions and offering a mini framework for validation. This package has been created to separate these two concerns since version 1.3.0. It’s the location for the standard, independent validation routines/functions in Commons Validator. First, the contents of this package do not depend on the framework aspect of Commons Validator. Second, we can use these on their own.

Let’s get familiar with some of the validator routines.

5. Date and Time Validators

The date and time validators can validate based on a specified format or use a standard format for a specified Locale. There are three options available:

  • Date Validator – validates dates and converts them to a java.util.Date type.
  • Calendar Validator – validates dates and converts them to a java.util.Calendar type.
  • Time Validator – validates times and converts them to a java.util.Calendar type.

5.1. Validating a Date Value

Let’s learn to use a date validator. First, let’s see how to use the validate() method. It returns the date if the input is valid else it returns null.

@Test
void givenDate_whenValidationIsCalled_thenChecksDate() {
    DateValidator validator = DateValidator.getInstance();
    String validDate = "28/01/2024";
    String invalidDate = "28/13/2024";

    assertNotNull(validator.validate(validDate, "dd/MM/yyyy"));
    assertTrue(validator.isValid(validDate, "dd/MM/yyyy"));

    assertNull(validator.validate(invalidDate, "dd/MM/yyyy"));
    assertFalse(validator.isValid(invalidDate, "dd/MM/yyyy"));

    GregorianCalendar gregorianCalendar = new GregorianCalendar(2024, Calendar.JANUARY, 28, 10, 30);
    gregorianCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = gregorianCalendar.getTime();

    assertEquals("28-Jan-2024", validator.format(date, "dd-MMM-yyyy"));

    TimeZone timeZone = TimeZone.getTimeZone("GMT+5");
    assertEquals("28/01/2024 15:30", validator.format(date, "dd/MM/yyyy HH:mm", timeZone));
}

This test verifies the DateValidator by checking valid and invalid date formats. First, it uses validate(). It returns a date if the input is a valid Date otherwise it returns null. Then, it uses isValid(). It returns a true if the input is a valid Date otherwise it returns false. After that, it formats a GregorianCalendar date to a string. Finally, it confirms the correct output, accounting for time zone adjustments.

6. Numeric Validators

The numeric validators validate according to a specified format. These either use a standard or a custom format for a specified Locale. In particular, they offer validators for different numeric data types. They offer the following validators: Byte Validator, Short Validator, Integer Validator, Long Validator, Float Validator, Double Validator, BigInteger Validator, and BigDecimal Validator.

6.1. Validating a Numeric Value

Generally, we use the IntegerValidator to validate numeric values.

@Test
void givenNumericString_whenValidationIsCalled_thenReturnsNumber() {
    IntegerValidator validator = IntegerValidator.getInstance();
    String pattern = "00000";
    int number = 1234;
    
    String formattedNumber = validator.format(number, pattern, Locale.US);
    
    assertEquals(number, validator.validate(formattedNumber, pattern));
    assertNotNull(validator.validate("123.4", Locale.GERMAN));
}

This test checks IntegerValidator functionality by formatting a number with a pattern and then validating it. First, it confirms that the formatted number matches the original. After that, it tests locale-specific validation, ensuring the validator correctly interprets numeric strings in different locales.

7. Currency Validators

The default implementation converts currency amounts to a java.math.BigDecimal. Additionally, it provides lenient currency symbol validation, meaning that currency amounts are valid with or without the symbol.

@Test
void givenCurrencyString_whenValidationIsCalled_thenReturnsCurrency() {
    BigDecimalValidator validator = CurrencyValidator.getInstance();
    
    assertEquals(new BigDecimal("1234.56"), validator.validate("$1,234.56", Locale.US));
    assertEquals("$1,234.56", validator.format(1234.56, Locale.US));
}

This test validates that CurrencyValidator correctly parses a U.S. currency string into a BigDecimal value and formats a numeric value back into the U.S. currency format. It ensures proper handling of locale-specific currency strings.

8. Other Validators

There are many such validators routines available from Apache Commons:

  • Regular Validators allow us to validate input using Java 1.4+ regular expression support, giving us the flexibility to define complex patterns for validation.
  • Check Digit routines assist us in validating and calculating check digits for various types of codes, such as EAN/UPC, credit card numbers, and ISBNs.
  • Code Validators provide comprehensive code validation, including checking the format, enforcing minimum and maximum length requirements, and validating check digits.
  • ISBN Validators help validate ISBN-10 and ISBN-13 formats, ensuring that the provided ISBNs are accurate.
  • IP Address Validators enable the validation of IPv4 addresses, ensuring they conform to the correct format and structure.
  • Email Address Validators provide robust validation for email addresses, ensuring they adhere to industry standards for correct formatting and structure.
  • URL Validators help validate URLs based on their scheme, domain, and authority, ensuring they are correctly formatted and valid.
  • Domain Name Validators validate domain names and check them against the official IANA TLD list, ensuring they are properly formatted and within the valid TLDs.

9. Conclusion

In this tutorial, first, we explored the Apache Commons Validator library, focusing on practical examples for validating dates, numbers, and currencies. Then, we demonstrated using specific validators like DateValidatorIntegerValidator, and CurrencyValidator through code snippets. Finally, we briefly introduced other available validators, showcasing the library’s versatility for common data validation needs.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)