October 14, 2020

Creating a custom validation for bean validation in spring boot

Creating a custom validation for bean validation in spring boot


Why we create a custom bean validation?

To test whether the input are valid one before the inputs reach our application.


How to create a custom annotation java code?

/**
 * Custom annotation
 */
package com.javabelazy.validators;

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

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author Java code
 *
 */

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = { OrderStatusValidator.class })
public @interface Status {

String message() default "Invalid order status";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}


@Target  denotes the context where the annotation type is applicable, here we mentioned on a method or a field.
@Retention  denotes the annotation is available at the run time.
@Constraint denotes the class where the validation  logic is implemented


How to create a custom validator?

/**
 *  Custom annotation validator class
 */
package com.javabelazy.validators;

import java.util.stream.Stream;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;



/**
 * @author Java source code
 *
 */
public class OrderStatusValidator implements ConstraintValidator<Status, String> {

@Override
public void initialize(Status constraintAnnotation) {
}

@Override
public boolean isValid(String orderStatus, ConstraintValidatorContext context) {
System.out.println(" ****** "+orderStatus);

if (orderStatus.isBlank()) {
return true;
}

boolean isValid = Stream.of(OrderStatus.values()).anyMatch(v -> v.name().equals(orderStatus));

return isValid;
}

}

How to use this annotation?


@Status
private String orderStatus;


Thanks





No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments