Wrong
Wrong

Reputation: 1253

Spring - Validate the field of a field

I am developing an API with Spring boot in which I have an object which has another object which has a field that I need to validate. These are the following:

CodigoDTO

public final class CodigoDTO {
    private String codigo;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String accion;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private UserDTO user;
}

UserDTO

public final class UserDTO {
    @ValidIdDocument(message = ERROR_DNI_NIE_FORMAT, checkNie = true, checkNif = true)
    private String username;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
    private String email;
    @Telefono
    private String tlf;
    private List<CategoriaVideosExplicativos> videosExplicativosVistos;
}

Validator interface

@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { TelefonoValidator.class })
@Documented
public @interface Telefono {
    String message() default ERROR_EMAIL_OR_TLF;
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

I am not including the validator interface because it's not relevant.

So, the thing is that I am sending a CodigoDTO object to my service, which has an UserDTO and whose tlf field must have a certain pattern. But the validator is not being triggered.

Please, notice that I know I can put the annotation in the UserDTO field in CodigoDTO instead but that doesn't feel like it's the right way to do it.

How could I achieve this? Thanks!

Upvotes: 1

Views: 540

Answers (2)

go to the service which consumes the object and annotate the object with @Valid. this should do the work.

public String myService( @RequestBody @Valid myObject) {
 //something  
}

Upvotes: 0

Mykola Yashchenko
Mykola Yashchenko

Reputation: 5361

If you want to validate the nested object, you have to annotate the field with @Validannotation:

public final class CodigoDTO {
    private String codigo;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String accion;
    @Valid
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private UserDTO user;
}

Upvotes: 3

Related Questions