I've to ignore the validation if value is not set on specific fields. For instance, I've name
, productId
, productSerial
, productDesc
and productPrice
In this, name
is mandatory field so always validation happens, rest of the fields are optional
but if value is set in these fields I've to validate. So I wrote custom validator for these optional fields and for name
I'm using javax.validation.constraints.NotNull
like this @NotNull(message = "Name cannot be null")
I get all these value in Map
from upstream app and set these value in my Java bean
and perform the validation
.
If all the fields are available in Map
, validation is working without any issue but if user set only name
which is mandatory and leave the optional field - my custom validator trying to validate and throwing NullPointerException
which I don't want.
I want my custom validator to validate if values are set on these optional fields else ignore the validation - I don't know how to achieve this :( It would be really appreciated if someone can help me with this and provide some sample example.
Working scenario:
Map<String,String> map = new HashMap();
map.put("name", "Apple"); // Always user will set this value - Mandatory
map.put("productId", "2342342"); // Optional but need to validate if this value is set
map.put("productSerial", "4334DDF43"); // Optional but need to validate if this value is set
map.put("productDesc", "iPhone"); // Optional but need to validate if this value is set
map.put("productPrice", "1303"); // Optional but need to validate if this value is set
// Once I get the map from upstream, I've to set the map value in my bean and validate
Product product = new Product();
product.setName(map.get("name"));
product.setProductId(map.get("productId"));
product.setProductSerial(map.get("productSerial"));
product.setProductDesc(map.get("productDesc"));
product.setProductPrice(map.get("productPrice"));
Getting NullPointerException when below scenario occurs
Map<String,String> map = new HashMap();
map.put("name", "Apple");
Product product = new Product();
product.setName(map.get("name"));
product.setProductId(map.get("productId"));
product.setProductSerial(map.get("productSerial"));
product.setProductDesc(map.get("productDesc"));
product.setProductPrice(map.get("productPrice"));
Please find my code below:
Product.java
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@ToString
@ValidParam
public class Product {
@NotNull(message = "Name cannot be null")
private String name;
private String productId;
private String productSerial;
private String productDesc;
private String productPrice;
}
ValidParam.java
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = ProductValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidParam {
String message() default "Invalid product data.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
ProductValidator.java
import org.springframework.beans.BeanWrapperImpl;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ProductValidator implements ConstraintValidator<ValidParam, Object> {
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
String productId = (String) new BeanWrapperImpl(value).getPropertyValue("productId");
String productSerial = (String) new BeanWrapperImpl(value).getPropertyValue("productSerial");
String productDesc = (String) new BeanWrapperImpl(value).getPropertyValue("productDesc");
String productPrice = (String) new BeanWrapperImpl(value).getPropertyValue("productPrice");
if ((productId != null || productSerial != null) || (productDesc != null && productPrice != null)) {
System.out.println("validation success");
return true;
} else {
System.out.println("validation failed");
return false;
}
}
}
Main.java
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// I get this Map from the upstream app
Map<String,String> map = new HashMap();
map.put("name", "Apple"); // Always user will set this value - Mandatory
map.put("productId", "2342342"); // Optional but need to validate if this value is set
map.put("productSerial", "4334DDF43"); // Optional but need to validate if this value is set
map.put("productDesc", "iPhone"); // Optional but need to validate if this value is set
map.put("productPrice", "1303"); // Optional but need to validate if this value is set
// Once I get the map from upstream, I've to set the map value in my bean and validate
Product product = new Product();
product.setName(map.get("name"));
product.setProductId(map.get("productId"));
product.setProductSerial(map.get("productSerial"));
product.setProductDesc(map.get("productDesc"));
product.setProductPrice(map.get("productPrice"));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Product>> violations = validator.validate(product);
for (ConstraintViolation<Product> violation : violations) {
System.out.println(violation.getMessage());
throw new NullPointerException(violation.getMessage());
}
}
}