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 DateValidator, IntegerValidator, and CurrencyValidator through code snippets. Finally, we briefly introduced other available validators, showcasing the library’s versatility for common data validation needs.
As usual, the full source code can be found over on GitHub.