DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Trending

  • Top JavaScript/TypeScript Gen AI Frameworks for 2026
  • Beyond Conversation: Mastering Context with Claude Code Skills and Agents
  • Designing Agentic Systems Like Distributed Systems
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Custom Validations

Spring Custom Validations

Spring makes our lives easier by providing us with built-in validations, but sometimes these are not enough. We will have a look at how we can add custom validations.

By 
Upanshu Chaudhary user avatar
Upanshu Chaudhary
·
Mar. 21, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
17.0K Views

Join the DZone community and get the full member experience.

Join For Free

While building applications and services it is very important that we maintain data integrity especially if they are data-centric. It is crucial to have control over the data that the application interacts with to ensure it behaves as expected.

There are many times the data received may get corrupted before reaching the application or the user may provide wrong inputs. This will not create a problem if validations are applied as the application can return invalid requests and may ask the user to provide correct fields, but in the absence of validations, it is sure to cause problems in some instances, as it may process incorrect data and disrupt the flow.

Spring makes our lives easier by providing us with some built-in validations like:

  • @NotNull
  • @NotBlank
  • @Size
  • @Min

But sometimes these are not enough. For example: when we need to validate a field that should only expect a 10 digit phone number. In cases like these, we need to build our custom validations.

In this blog, we will have a look at how we can add custom validations with the help of an example.

Prerequisites

  • Setup a Spring Boot Java 8 project using Spring Initializer.

The pom should look like this:

Java
 




x


 
1
<dependencies>
2
        <dependency>
3
            <groupId>org.springframework.boot</groupId>
4
            <artifactId>spring-boot-starter-validation</artifactId>
5
        </dependency>
6
        <dependency>
7
            <groupId>org.springframework.boot</groupId>
8
            <artifactId>spring-boot-starter-web</artifactId>
9
        </dependency>
10
        <dependency>
11
            <groupId>org.hibernate</groupId>
12
            <artifactId>hibernate-validator</artifactId>
13
            <version>6.0.10.Final</version>
14
        </dependency>
15
    </dependencies>
16

          
17
    <build>
18
        <plugins>
19
            <plugin>
20
                <groupId>org.springframework.boot</groupId>
21
                <artifactId>spring-boot-maven-plugin</artifactId>
22
            </plugin>
23
        </plugins>
24
    </build>



Use Case

For this example, we will build a simple application that will provide us with an endpoint to POST data.

The Request body POJO looks like this. Here we have defined 3 fields which are name, customerId, and phoneNumber. We will validate customerId and phoneNumber by making our custom validations.

Defining Annotations

The first step is to define our Annotation with @interface.

- @Constraint: This is the annotation where we provide the class which will validate our field.

- @Retention: It defines at what point the annotation should be discarded. We will provide RetentionPolicy as RUNTIME so that it will be available to JVM during runtime.

- @Target: As the name suggests, here we define where this annotation can be used.

- @Documented: It ensures that classes using this annotation show this in their generated JavaDoc. Removing it won’t affect our code but it is a best practice to use it.

There are 3 attributes inside our annotation which are message(), groups() and payload(). Out of these we only need to know about message() for now which is the default message that will be given in case the validation fails.

Validation Class

This is the class where we will define the validation logic and provided in @Constraints.

The first step is to implement the ConstraintValidator<>.

An interface that provides us with two methods to @Override that initialize() and isValid().

Here we do not need to initialize any value for our validation hence we will not implement the initialize().

Java
 




xxxxxxxxxx
1
15


 
1
public class CustomerIdValidator implements ConstraintValidator<CustomerId, String> {
2

          
3
    private static final Logger log = LoggerFactory.getLogger(CustomerIdValidator.class);
4

          
5
    @Override
6
    public boolean isValid(String customerId, ConstraintValidatorContext constraintValidatorContext) {
7
        if(!customerId.isEmpty() && customerId.matches(Constants.CUSTOMER_ID_REGEX)) {
8
            log.info("Received valid customerId of type 'UUID'");
9
            return true;
10
        } else {
11
            log.error("Received invalid customerId");
12
            return false;
13
        }
14
    }
15
}



Implementing the Validation Annotation

As we have already seen in our POJO above we have applied @CustomerId on our customerId field, hence applying the validation.

Now that we have defined the constraints, we will now define our controller, which will accept Person as a body simply log the fields for this example.

Note: @Valid is very important here as it triggers the validation on the request.

Java
 




xxxxxxxxxx
1
12


 
1
@RestController
2
@RequestMapping("person")
3
public class ValidationController {
4

          
5
    private static final Logger logger = LoggerFactory.getLogger(ValidationController.class);
6

          
7
    @PostMapping
8
    public Person create(@Valid @RequestBody Person person) {
9
        logger.info("Received valid customerId {} and phone number {} ", person.getCustomerId(), person.getPhoneNumber());
10
        return person;
11
    }
12
}



Postman POST Request

Postman POST RequestLog

Postman Log

You can find this code here.

Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook