using binder.forField with @NotNull annotation


If my model attribute is annotated with @NotNull, and i bind the component using binder.bind(myComponent, MyModel::getter, MyModel::setter) , the requiredfieldvalidator is not set automatically. I have to use the form binder.forField().asRequired().bind() . But that defeats the purpose of annotating my model class. Am i misunderstanding how this should work?

forField with method references does not work on the validation API, only the binding via properties / strings is supported

@supportive-urial If you want to use BeanValidationBinder you must use the property name in the binder:


Ok thanks for confirming. Sounds like a good usecase for Lombok’s @FieldNameConstants then !

Vaadin has two variants of Binder. The regular one is class Binder, which does not use validation annotations. The another one is class BeanValidationBinder, which is using JSR-303 annotations automatically. If you want to use annotations as your primary method of defining valudation constraints, you should use that.

Indeed, but the “catch” as I just learned here is that even when using BeanValidationBinder, if you don’t use above form .forField().bind() or .bindInstanceFields() there is no JSR303 validation happening. It’s slightly surprising intuitively perhaps, but i understand why.

Therre is a section in the documentation about JSR303 Binding Beans to Forms | Data Binding | Vaadin Docs

Btw. I never use the form binder.bind(myComponent, MyModel::getter, MyModel::setter

I always use binder.forField().bind(). It’s much clearer IMO

Yes, i had read that section but nowhere it actually says that it is mandatory to use that particular binding syntax to get jsr303 validation working.

Initially we were using bindInstanceFields() but noticed that it was hard for people to grasp this concept, as powerful as it may appear it’s a lot of magic behind the scenes. Also very easy to break things unknowingly. So then we moved to the manual way of binding, but with compile time safety in mind i chose the syntax using the getter and setter method references.

I agree about the binder.forField() syntax though, it’s the clearest form. And with the help of Lombok we manage to get it compile-time checked as well !

And with the help of Lombok we manage to get it compile-time checked as well !
Beware that with Lombok it is easy to mess up with bean identity etc. so my preference is usually not to use it all. If you know how each Lombok annotation actually works internally you can avoid the pitfals, but if you do not, do not use it.