I have a DTO that looks something like this:
class VehicleDto {
private String type;
private Car car;
private Bike bike;
}
Now depending on the type, I need to validate on at least one of Car and Bike.
Both cannot be present in the same request.
How can I do that?
Having two fields in class, while only one of them can present, seems like a design smell for me.
But if you insist on such design - you can create a custom Validator for your VehicleDto class.
public class VehicleValidator implements Validator {
public boolean supports(Class clazz) {
return VehicleDto.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
VehicleDto dto = (VehicleDto) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type",
"error.message.for.type.field");
if (null != dto.getType()
&& null != dto.getCar()
&& null != dto.getBike()) {
switch(dto.getType()) {
case "car":
errors.rejectValue("bike", "error.message.for.bike.field");
break;
case "bike":
errors.rejectValue("car", "error.message.for.car.field");
break;
}
}
}
}
Also, see Spring documentation about validation:
Validation using Spring’s Validator interface
Resolving codes to error messages
Injecting a Validator
For example, if we want to check whether my TaskDTO object is valid, by comparing its two attributes dueDate and repeatUntil , following are the steps to achieve it.
dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
DTO class:
#ValidTaskDTO
public class TaskDTO {
#FutureOrPresent
private ZonedDateTime dueDate;
#NotBlank(message = "Title cannot be null or blank")
private String title;
private String description;
#NotNull
private RecurrenceType recurrenceType;
#Future
private ZonedDateTime repeatUntil;
}
Custom Annotation:
#Constraint(validatedBy = {TaskDTOValidator.class})
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface ValidTaskDTO {
String message() default "Due date should not be greater than or equal to Repeat Until Date.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Constraint Validator:
public class TaskDTOValidator implements ConstraintValidator<ValidTaskDTO, TaskDTO> {
#Override
public void initialize(ValidTaskDTO constraintAnnotation) {
}
#Override
public boolean isValid(TaskDTO taskDTO, ConstraintValidatorContext constraintValidatorContext) {
if (taskDTO.getRecurrenceType() == RecurrenceType.NONE) {
return true;
}
return taskDTO.getRepeatUntil() != null && taskDTO.getDueDate().isBefore(taskDTO.getRepeatUntil());
}
}
Make sure that you have #Valid in front of RequestBody of a postmapping method in your RestController. Only then the validation will get invoked:
#PostMapping
public TaskReadDTO createTask(#Valid #RequestBody TaskDTO taskDTO) {
.....
}
I hope this helps. If you need a detailed explanation on steps, have a look at this video
Related
I have the following controller:
public interface SaveController {
#PostMapping(value = "/save")
#ResponseStatus(code = HttpStatus.CREATED)
void save(#RequestBody #Valid SaveRequest saveRequest);
}
SaveRequest corresponds to:
public class SaveRequest {
#NotNull
private SaveType type;
private String name;
}
and SaveType:
public enum SaveType {
DAILY, WEEKLY, MONTHLY;
}
The controller does not receive the enum itself, but a camelCase String. I need to convert that String into the corresponding enum. For instance:
daily should become DAILY.
weekly should become WEEKLY.
monthly should become MONTHLY.
Any other String should become null.
I've tried using the Spring Converter class, which does not work when the enum is inside an object (at least I don't know how to make it work in such times).
I honestly don't know what else to try
https://www.baeldung.com/jackson-serialize-enums
This site should probably give you plenty of options.
Best is probably something like this:
public enum SaveType {
DAILY, WEEKLY, MONTHLY;
#JsonCreator
public static SaveType saveTypeforValue(String value) {
return SaveType.valueOf(value.toUpperCase());
}
}
What you require is to have custom annotation with a custom validation class for Enum.
javax.validation library doesn't have inbuilt support for enums.
Validation class
public class SaveTypeSubSetValidator implements ConstraintValidator<SaveTypeSubset, SaveType> {
private SaveType[] subset;
#Override
public void initialize(SaveTypeSubset constraint) {
this.subset = constraint.anyOf();
}
#Override
public boolean isValid(SaveType value, ConstraintValidatorContext context) {
return value == null || Arrays.asList(subset).contains(value);
}
}
interface for validation annotation with validation message
#Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = SaveTypeSubSetValidator.class)
public #interface SaveTypeSubset {
SaveType[] anyOf();
String message() default "must be any of {anyOf}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Usage
#SaveTypeSubset(anyOf = {SaveType.NEW, SaveType.OLD})
private SaveType SaveType;
This is one way. More ways are mentioned in this article.
I have the following class :
class ContactInformation {
String phone;
String email;
}
which is used in the following classes :
class Person {
#Valid
ContactInformation contactInformation;
}
class Station {
#Valid
ContactInformation contactInformation;
}
The thing is that any instance of Person must have an email, but it is an optional information for Station. Do I have a way to define this at owner level to avoid duplicate the class ContactInformation ?
Instead of the field level validator you can add the Type level validator.
Steps:
Define Type level annotation
Write Validator for new annotation
Introduce your type with a new annotation
Define:
#Constraint(validatedBy = {PersonClassOptionalEmailValidator.class})
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface PersonalEmailValid {
String message() default "Invalid Email address";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Writing Custom Validator:
public static class PersonClassOptionalEmailValidator implements ConstraintValidator<PersonalEmailValid, Person> {
// Test Email validator, you should check prope regex for production
public static final String EMAIL_REGEX = "^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+$";
private final Pattern pattern;
public PersonClassOptionalEmailValidator() {
pattern = Pattern.compile(EMAIL_REGEX);
}
#Override
public boolean isValid(Person person, ConstraintValidatorContext constraintValidatorContext) {
if (person.contactInformation != null) {
return pattern.matcher(person.contactInformation.email).matches();
}
return false;
}
}
Introduce new annotation to class
#Getter
#Setter
#NoArgsConstructor
#PersonalEmailValid
static class Person {
#Valid
ContactInformation contactInformation;
}
Reference
Gist
I want to create condition based validation in spring validator.
I have one UserDTO class in that there are two DTO class with #Valid annotation.
If I pass isPrimary true then it should validate only primaryDTO bean and ignoring secendoryDTO validations.
public class UserDTO {
#Valid
private PrimaryDTO primaryDTO;
#Valid
private SecendoryDTO secendoryDTO;
private boolean isPrimary;
}
public class PrimaryDTO {
#NotEmpty(message = "Please enter email.")
#Email(message = "Please enter a valid email.")
private String email;
}
public class SecendoryDTO {
#NotEmpty(message = "Please enter phone.")
private String phone;
}
Please Guide.
Thanks
If your validation depends on multiple fields (eg. isPrimary and either primaryDTO or secondaryDTO), then the only solution is to write a custom validator on classlevel (UserDTO) which will implement the conditional validation itself.
For example, create an annotation:
#Documented
#Retention(RUNTIME)
#Target({ANNOTATION_TYPE, TYPE})
#Constraint(validatedBy = SecondaryValidator.class)
public #interface ValidSecondary {
String message() default "Invalid secondary";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And create a validator that only validates the secondaryDTO field when isPrimary() is false:
#Component
public class SecondaryValidator implements ConstraintValidator<ValidSecondary, UserDTO> {
private Validator validator;
public SecondaryValidator(Validator validator) {
this.validator = validator;
}
#Override
public boolean isValid(UserDTO userDTO, ConstraintValidatorContext constraintValidatorContext) {
if (userDTO.isPrimary()) {
return true;
} else {
return validator.validate(userDTO.getSecondaryDTO()).isEmpty();
}
}
}
After that, you can remove the #Valid annotation from the secondaryDTO field and add the #ValidSecondary annotation on top of your UserDTO:
#ValidSecondary // Add this
public class UserDTO {
#Valid
private PrimaryDTO primaryDTO;
private SecondaryDTO secondaryDTO; // No more #Valid
private boolean primary;
}
However, in this case you'll lose any constraint violation message from within the SecondaryDTO, if you want to have some kind of passing through mechanism, you can add the violations to the constraintValidatorContext within the isValid() method, for example:
Set<ConstraintViolation<SecondaryDTO>> violations = validator.validate(userDTO.getSecondaryDTO());
violations.forEach(violation -> constraintValidatorContext
.buildConstraintViolationWithTemplate(violation.getMessage())
.addConstraintViolation());
A little greedy question here, hope this one could also help others who want to know more about annotation validation
I am currently studying Spring, and for now, I am planning to try out the customize annotated validation.
I have searched a lot and now I know there are mainly two kinds of validations, one is used for the controller, and the other is the annotation method using #Valid
So here's my scenario:
Suppose I have two or more fields which can be null when they are ALL NULL.
But only when one of those fields contains any value except an empty string, those fields are required to have input. And I had two ideas but didn't know how to implement them correctly.
Here's the Class Example:
public class Subscriber {
private String name;
private String email;
private Integer age;
private String phone;
private Gender gender;
private Date birthday;
private Date confirmBirthday;
private String birthdayMessage;
private Boolean receiveNewsletter;
//Getter and Setter
}
Suppose I want that the birthday and confirmBirthday field need to be both null or the oppose, I may want to annotate them using one annotation for each of them and looks like this:
public class Subscriber {
private String name;
private String email;
private Integer age;
private String phone;
private Gender gender;
#NotNullIf(fieldName="confirmBirthday")
private Date birthday;
#NotNullIf(fieldName="birthday")
private Date confirmBirthday;
private String birthdayMessage;
private Boolean receiveNewsletter;
//Getter and Setter
}
So i do need to create the validation Annotation like this:
#Documented
#Constraint(validatedBy = NotNullIfConstraintValidator.class)
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.METHOD, ElementType.FIELD })
public #interface NotNullIf {
String fieldName();
String message() default "{NotNullIf.message}";
Class<?>[] group() default {};
Class<? extends Payload>[] payload() default {};
}
And After that i will need to create the Validator itself:
public class NotNullIfConstraintValidator implements ConstraintValidator<NotNullIf, String>{
private String fieldName;
public void initialize(NotNullIf constraintAnnotation) {
fieldName = constraintAnnotation.fieldName();
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if(value == null) {
return true;
};
//TODO Validation
return false;
}
}
So how can it be achievable?
For another idea using the same Class as an example which said that i want birthday, confirmBirthday and birthdayMessdage can only be null or the oppose at the same time.
I may require to use the class annotated validation this time for cross-field validation.
Here's how i suppose to annotate the class:
#NotNullIf(fieldName={"birthday", "confirmBirthday", "birthdayMessage"})
public class Subscriber {
//Those field same as the above one
}
So when one of that field is not null, the rest of them also needs to be entered on the client size.
Is it Possible?
I have read this article: How to access a field which is described in annotation property
But I still confusing on how the annotation validation works from those elements I listed above.
Maybe I need some detail explanation on that code or even worse I may need some basic concept inspection.
Please Help!
For this you can use a type level annotation only because a field level annotation has no access to other fields!
I did something similar to allow a choice validation (exactly one of a number of properties has to be not null). In your case the #AllOrNone annotation (or whatever name you prefer) would need an array of field names and you will get the whole object of the annotated type to the validator:
#Target(ElementType.TYPE)
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = AllOrNoneValidator.class)
public #interface AllOrNone {
String[] value();
String message() default "{AllOrNone.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class AllOrNoneValidator implements ConstraintValidator<AllOrNone, Object> {
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
private String[] fields;
#Override
public void initialize(AllOrNone constraintAnnotation) {
fields = constraintAnnotation.value();
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
long notNull = Stream.of(fields)
.map(field -> PARSER.parseExpression(field).getValue(value))
.filter(Objects::nonNull)
.count();
return notNull == 0 || notNull == fields.length;
}
}
(As you said you use Spring I used SpEL to allow even nested fields access)
Now you can annotate your Subscriber type:
#AllOrNone({"birthday", "confirmBirthday"})
public class Subscriber {
private String name;
private String email;
private Integer age;
private String phone;
private Gender gender;
private Date birthday;
private Date confirmBirthday;
private String birthdayMessage;
private Boolean receiveNewsletter;
}
Consider adding compile-time validation for the field names. For example, in #Arne answer the strings "birthday" and "confirmBirthday" are not guaranteed to match actual field names at compile time. If you want to add that functionality, here's an example from my code for a slightly different example that assumes there are exactly two fields. The purpose is to assert that two fields are ordered... For example, it could be used for "beginDate" and "endDate".
public class OrderedValidator extends AbstractProcessor implements ConstraintValidator<Ordered, Object>
{
private String field1;
private String field2;
private Messager messager;
public void initialize(Ordered constraintAnnotation)
{
this.field1 = constraintAnnotation.field1();
this.field2 = constraintAnnotation.field2();
}
#Override
public synchronized void init(ProcessingEnvironment processingEnv)
{
super.init(processingEnv);
messager = processingEnv.getMessager();
}
#SuppressWarnings("unchecked")
public boolean isValid(Object value, ConstraintValidatorContext context)
{
Object field1Value = new BeanWrapperImpl(value).getPropertyValue(field1);
Object field2Value = new BeanWrapperImpl(value).getPropertyValue(field2);
boolean valid = true;
if (field1Value != null && field2Value != null)
{
if (field1Value.getClass().equals(field2Value.getClass()))
{
valid = ((Comparable) field1Value).compareTo((Comparable) field2Value) <= 0;
}
}
return valid;
}
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Ordered.class))
{
if (annotatedElement.getKind() != ElementKind.CLASS)
{
messager.printMessage(Diagnostic.Kind.ERROR, "Only classes can be annotated with " + Ordered.class.getSimpleName());
return true;
}
TypeElement typeElement = (TypeElement) annotatedElement;
List<? extends Element> elements = typeElement.getEnclosedElements();
boolean field1Found = false;
boolean field2Found = false;
for (Element e : elements)
{
if (e.getKind() == ElementKind.FIELD && field1 != null && field1.equals(e.getSimpleName()))
{
field1Found = true;
}
else if (e.getKind() == ElementKind.FIELD && field2 != null && field2.equals(e.getSimpleName()))
{
field2Found = true;
}
}
if (field1 != null && !field1Found)
{
messager.printMessage(Diagnostic.Kind.ERROR, "Could not find field named " + field1);
return true;
}
if (field2 != null && !field2Found)
{
messager.printMessage(Diagnostic.Kind.ERROR, "Could not find field named " + field2);
return true;
}
}
return false;
}
}
I want to use standard javax.validation for properties and my own validation for functional validations. The simplified subclass looks like:
public class TestData extends AbstractData {
#NotNull
Long id = null;
#NotNull
Long value = null;
public Set<ConstraintViolation<TestData>> validateFunctional() {
Set<ConstraintViolation<TestData>> violations = new HashSet<>();
if ( id < 42 || value > 4711 ) {
//--- here comes another question: how do I create a constraint violation?
}
return violations;
}
}
This is the base class:
public abstract class AbstractData {
public Set<ConstraintViolation<?>> validate() {
//--- First validate single properties
Set<ConstraintViolation<?>> violations = validator.validate( this );
}
//--- Single props OK => validate functional
if ( violations.isEmpty()) {
violations.add( validateFunctional());
}
return violations;
}
Gives the error
Type mismatch: cannot convert from Set<ConstraintViolation<AbstractData>> to Set<ConstraintViolation<?>>
I believe this should be what you are looking for:
public abstract class AbstractData<T> {
abstract T getObj();
public Set<ConstraintViolation<T>> isValid(){
//do your custom validations if needed
return Validation.buildDefaultValidatorFactory()
.getValidator().validate(getObj());
}
}
POJO to be validated:
public class Bar extends AbstractData<Bar> {
#NotNull
private Long id;
#NotNull
private Long value;
#CustomConstraint
private Long customConstraint;
#Override
public Bar getObj() {
return this;
}
}
Then simply call bar.isValid().
EDIT:
Regarding your question about a custom constraint, you can do it like this:
#Constraint(validatedBy = {CustomConstraint.CustomConstraintValidator.class})
#Target({ElementType.FIELD, ElementType.PARAMETER})
#Retention(value = RetentionPolicy.RUNTIME)
#Documented
public #interface CustomConstraint {
String message() default "Invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class CustomConstraintValidator implements ConstraintValidator<CustomConstraint, Long> {
#Override
public void initialize(CustomConstraint customConstraint) {
}
#Override
public boolean isValid(Long obj, ConstraintValidatorContext constraintValidatorContext) {
if (obj == null)
return false;
if (obj < 10)
return false;
return true;
}
}
}
In this example, if I annotate a Long field with #CustomConstraint and pass the value lower than 10 or null, the validator will return an error, otherwise it won't. The validation itself is useless in the example, I just put up something to serve as a snippet for you to build yours.