Add Bean Validation with Micronaut (Java)

I want to use my own Bean Validation with Micronaut

I had to create my own validator in my work, and since it is a new framework, I had a lot of trouble as a beginner of && Java who has no materials at all.

As a result, I made a note of what I expected.

Background

The current task requires such an implementation, which is common for input validation.

  1. Make sure that certain parameters of the request match the specified regular expression
  2. If not, returns an error response with a specific error message

Elementary? I think that Micronaut can be realized by Pattern (regexp =" pattern ", message =" message "), but in the current project, it is processed by a handler for each annotation, and this implementation was inconvenient.

Implementation

** Added on 2020/03/04 It is necessary to add @Singleton to the Validator class, so I added it. ** **

Annotation + validator

Bean Validation to check if any of the following is satisfied for the EmployeeNumber field

--Value is NULL --Shape of UXXXX, NXXX, KXXXX

package com.myproject.annotation;

import io.micronaut.core.annotation.AnnotationValue;
import io.micronaut.validation.validator.constraints.ConstraintValidator;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({FIELD})
@Retention(RUNTIME)
@Documented

@Constraint(validatedBy = {EmployeeNumberValidator.class})
public @interface EmployeeNumber {
    String message() default "Employee number is the first letter of the company name+Please enter in 4-digit half-width numbers.";
}

@Singleton
class EmployeeNumberValidator
implements ConstraintValidator<EmployeeNumber, String> {
    private static final Pattern EmployeeNumberPattern = Pattern.compile("^[UNK]\\d{4}+$");

    @Override
    public boolean isValid(@Nullable String value, @Nonnull AnnotationValue<EmployeeNumber> annotationMetadata, @Nonnull io.micronaut.validation.validator.constraints.ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return EmployeeNumberPattern.matcher(value).matches();
    }
}

This time, the validator and annotation are put together, but if you want to cut out to another file, set the validator to public and ʻimport` on the annotation side.

The annotations attached to the annotation definition interface itself are not specific to Micronaut and will appear immediately after searching, so I will not explain them (I do not understand well).

Request entity that uses annotation

package com.myproject.request;

import com.myproject.annotation.EmployeeNumber;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import io.micronaut.core.annotation.Introspected;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Introspected
@Data
@JsonFormat
public class EmployeeSearchRequest {
    @NotNull
    private String officeCode;
    private String employeeId;
    @EmployeeNumber
    private String employeeName;
}

Where I stumbled

Initially, when I implemented it by referring to the article that implements javax.validation.ConstraintValidator, the phenomenon that it was not picked up by the handler of ConstraintViolationException occurred even though it was annotated.

** ʻO.micronaut.validation.validator.constraints.ConstraintValidator` is implemented ** It seems that it was necessary to create a validator.

This was resolved by specifying it in the annotation @Constraint.

Recommended Posts

Add Bean Validation with Micronaut (Java)
[Java] Article to add validation with Spring Boot 2.3.1.
Java (add2)
Easy input check with Bean Validation!
Java (add)
Add index with Java8 Stream.map (tuple version)
Create your own validator with Bean Validation
Introduce Bean Validation 2.0 into Java SE programs
Try DI with Micronaut
Install java with Homebrew
[Java] Correlation check without creating annotations by Bean Validation
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
JSON validation with JSON schema
Switch java with direnv
[Java] Initialize, add, get
Download Java with Ansible
Self-made Validation with Spring
Let's scrape with Java! !!
Build Java with Wercker
Hello World with Micronaut
Serverless Function with Micronaut
java: Add date [Note]
Get started with serverless Java with the lightweight framework Micronaut!
Endian conversion with JAVA
Create a simple CRUD with SpringBoot + JPA + Thymeleaf ③ ~ Add Validation ~
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Bean mapping with MapStruct Part 1
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Install Java 7 with Homebrew (cask)
Process validation messages with Decorator
[Java] JSON communication with jackson
Bean mapping with MapStruct Part 3
Try DB connection with Java
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Bean mapping with MapStruct Part 2
Version control Java with SDKMAN
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
Access Apache Kafka with Micronaut
[Java] Content acquisition with HttpCliient
Java version control with jenv
Troubleshooting with Java Flight Recorder
Java addition excel data validation
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate