简体   繁体   中英

Spring DTO validation using ConstraintValidator

The DTO that I use is annotated with javax.validation annotations

For example

@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentDTO {

@NotEmpty
private String name;

@Positive
private Long studentId;

}

What if I have to validate using ConstraintValidator for StudentDTO

Spring MVC has the ability to automatically validate @Controller inputs. In previous versions it was up to the developer to manually invoke validation logic.

But in your case , you are trying to validate a DTO object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator.

or you can manually invoke the validator on a bean like :

@AutoWired
Validator validator;
...

validator.validate(book);

You can define a custom validator in springboot for model classes if you want and use annotations :

@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
    String message() default "Invalid data";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and then define a validator class like :

public class CustomDataValidator implements
  ConstraintValidator<CustomDataConstraint, String> {

    @Override
    public void initialize(CustomDataConstraint data) {
    }

    @Override
    public boolean isValid(String field,
      ConstraintValidatorContext cxt) {
        return field!= null;
    }

}

Your validator class must implement the ConstraintValidator interface and must implement the isValid method to define the validation rules, define the validation rules can be anything as you wish.Then, you can simply add the annotation to your field like :

@CustomDataConstraint 
private String name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM