Create custom validation based on UUID

In this tutorial, let’s learn how to create custom validation for UUID.

Many a time we use validations for DTO so the data being passed is clean before copying same into entities as the first level of the filter.

We might often have used annotations such as @NotNull @NotEmpty @NotBlank and so on, but how about creating one which is not there at present.

Below we have created a custom annotation.

UUID.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;

@Target(ElementType.FIELD)
@Constraint(validatedBy={})
@Retention(RetentionPolicy.RUNTIME)
@Pattern(regexp="^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$|")
@ReportAsSingleViolation
public @interface UUID {
    String message() default "Invalid UUID";
}

Here UUID validation is written using regex such that when the string on which UUID is being validated is empty then it does nothing else if the value is present then it makes sure it’s a valid UUID format or display an error message.


To achieve that the simple hack is to add pipe ( | ) at the end of the regex.


Also, note that @ReportAsSingleViolation is used so that custom error messages can be set else @pattern will override the message.

Now we can use the annotation created above in below DTO as below.

SampleDTO.java

public class SampleDTO {

 @UUID
 private String id;

}

Leave a Reply

Your email address will not be published. Required fields are marked *

sixteen + five =