jakartaee / validation

Jakarta Validation
http://beanvalidation.org
Apache License 2.0
127 stars 54 forks source link

Make adding constraints easier #184

Closed Serkan80 closed 11 months ago

Serkan80 commented 1 year ago

Imho, adding custom constraints should be easier than it is now. It is cumbersome to define an annotation and an implementation class if you just want to compare some fields with each other.

why is something like this not possible ?

class Person {
   @Size(min=3)
   String lastname;

   @PastOrPresent
   LocalDate birthday:

   @Pattern(“\\d{8}”)
   String ssn;

   @Constraint
    boolean validate() {
       return ssn != null || (birthday != null && lastname != null);
    }
}

The validate method will also be invoked as part of validating this bean after its fields have been validated. And the method annotated with @Constraint should always return a boolean.

This is much easier to use and everything you need from the bean is there.

gunnarmorling commented 1 year ago

You can already do pretty much that, by putting the existing @AssertTrue constraint to a method e.g. named isValid(). I think this should address your requirement?

Serkan80 commented 1 year ago

That doesn’t work unfortunately.

I’ve done the following and assertTrue doesn’t get triggered:

class MyDto {
    @Valid
   @NotNull
    Person person; // —-> contains @assertTrue on method
}

My Rest controller:

@POST
public void save(@Valid MyDto dto) {}

AssertTrue doesn’t get triggered.

And I’m using Quarkus 3.2.0, altogether with Jakarta Bean Validation.

gunnarmorling commented 1 year ago

How does that method on Person look like? It must conform to the JavaBeans naming convention.

Serkan80 commented 1 year ago

It was called something like checkRequiredFields().

And do you also need to have a field for that method ?

gunnarmorling commented 1 year ago

Yeah, so that name doesn't work. Boolean JavaBeans property getters must be named isXyz(). No field is needed for that.

Serkan80 commented 1 year ago

Ok thx, I will try that (probably tomorrow). Thx for the feedback.