0

I receive list of domain object ids deserialized from JSON client request body:

@JsonProperty("workgroups")
private List<WorkgroupId> workgroupIds = new ArrayList<>();

I need to validate these ids in org.springframework.validation.Validator.

for (WorkgroupId workgroupId : project.getWorkgroupIds()) {
  if (!domainObjectTools.doesWorkgroupExist(workgroupId)) {
// reject this invalid value here...
  }
}

Question

How to reject invalid value in org.springframework.validation.Errors?

jnemecz
  • 3,171
  • 8
  • 41
  • 77

2 Answers2

-1

Validator interface:

@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { CustomValidatorValidator.class })
@Documented
public @interface CustomValidator{
    String message() default "Put here your default message";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

ValidatorImplementation:

public final class CustomValidatorValidator implements ConstraintValidator<CustomValidator, List<WorkgroupId>> {

    @Override
    public void initialize(CustomValidator constraintAnnotation) {

    }

    @Override
    public boolean isValid(List<WorkgroupId> yourlist, ConstraintValidatorContext context) {
        if (yourlist== null)
            return true;
        else
            return yourlist.stream().anyMatch(s -> /* filter here as you want */);
    }
}

Notice we return true if the field is null, I do it like this because I just put @NotNull constraint if I need not to be null so I have more control over the constraint.

Finally:

@JsonProperty("workgroups")
@CustomValidator
private List<WorkgroupId> workgroupIds = new ArrayList<>();

P.S: I don't understand why you initialize the list in this last code. If that's a field you're supposed to receive through the request then you don't need to initialize it, the json deserializer will initialize it with the incoming field in the json.

Wrong
  • 1,195
  • 2
  • 14
  • 38
-1

You can use reject() and/or rejectValue() along with the field/error code/defaultMessage or along with a custom validator to reject the values.

Yuvi Jum
  • 69
  • 1
  • 5