DEV Community

Ninan Kara
Ninan Kara

Posted on

Day 2: Java Validation

Intro

Recently, I focus on building a REST API using Spring Boot, Java and Swagger.
We all know that REST API involves Request and Response parameter in it. I was amazed at how Java provides validation to prevent repeatable line of code.
Before annotation era, we always do the validation using if else instruction. If this field is null then throw exception, if A is null then B becomes mandatory, and so on. Imagine you create hundreds API involves hundreds field parameters?

Validation annotation

So, Java gives you a solution. You can put validation annotation attached with field. If you create custom validation, you can put it also in class level. I will note down the basic one. Following are the common annotation used for field validation on Request parameters.

  • @ NotBlank -> validates that value is not null. can be used in any type of field. usually String type
  • @ Size -> validates size/length of value. Usually applied for integer type. It has attribute min and max
  • @ Pattern -> to validate pattern using regex. I used this one a lot. It is very convenience to use other than comparing String with equals method. The challenge is creating the regex itself. You can simulate it here before use it. Probably I will write about this part in separate post.

Custom Validation

If your requirement getting complicated, and no basic annotation can accommodate it, you may create your own validation. This post is a good start .
I will share one of my custom validation later :D

Some example

@Pattern(regexp="^[0-9]*$")
@NotBlank
@Size(max = 20)
String myNumber;

@MyCustomValidation
String myCode;

Top comments (0)