Vassilis Blazos
Vassilis Blazos

Reputation: 1610

How to use the same form DTO, with different validation annotations? How to avoid double code?

Which is the best practice to write DTO and follow different validated annotations, without double my code? Below attached a simple example, that I want to avoid:

public class AddressForm1 {

    @NotEmpty
    private String address;

    @NotNull
    @Max(23)
    @Min(30)
    private BigDecimal lng;

    // getters & setters
}

and;

public class AddressForm2 {

    // removed annotation, empty value permitted
    private String address;

    @NotNull
    @Max(43)
    @Min(50)
    private BigDecimal lng;

    //getters & setters
}

Upvotes: 2

Views: 2013

Answers (2)

Kennedy Oliveira
Kennedy Oliveira

Reputation: 2281

You can use Groups, and validate some annotations only when you need, check this Group Hibernate Doc

Upvotes: 1

Master Slave
Master Slave

Reputation: 28559

You can use validation group, and group your constraints. Than decide which set of constraints you'll apply using the @Validated annotation, with the appropriate group specified

Check the example in http://www.javacodegeeks.com/2014/08/validation-groups-in-spring-mvc.html

Upvotes: 2

Related Questions