0

I have a model object annotated with Java validation annotations.

class Criteria{
    @NotEmpty String id;    
    @NotEmpty String name;
    String fileName;
    String hours;   
}

As per the business requirement, either fileName or hours field will be populated, to validate which I have a custom validator 'CriteriaValidator' written.

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

The model above is passed in as input parameter for a method which is also annotated with @Valid and @ValidCriteria.

public void update(@Valid @ValidCriteria Criteria criteria){...}

The issue I have is with 2 annotations in the method. I have to add @Valid in order to check constraints annotated within the class. My custom validator checks only for the existence of one of the 2 fields: filename or hours.

The question I have is, how do I have a single annotation @ValidCriteria which validates my special requirement as well as the @NotEmpty fields in the object.

I tried adding @Valid in my custom constraint @ValidCriteria, however I get the error '@Valid is not applicable to annotation type'

1 Answer 1

1

The @ValidCriteria annotation should be on the Criteria class:

@ValidCriteria
class Criteria{
    @NotEmpty String id;    
    @NotEmpty String name;
    String fileName;
    String hours;   
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. It works perfectly and my method signature only has @Valid constraint now.
Sorry, but if I want to validate class to which I dont have access and cannot annotate with validation annotation? I created custom annotation and want use it to validate external class in controller method parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.