How to have on-demand validation?

I’ve a binder like this binder.forField(unitName).asRequired() .withValidator(s -> { boolean unitNameAlreadyExists = unitService.isUnitNameAlreadyExists(s);"unitNameAlreadyExists ? {}", unitNameAlreadyExists); return !unitNameAlreadyExists; },"Unit name already exists") .bind(Unit_.UNIT_NAME);. This gets validated immediately after the value is changed which I do not want to. Also, when user tries to edit this field, it shows unit already exists. I want this validation only when the save button is clicked. How to let the binder to do so ?

Just add your logic to the button click.

I’ve the binder.validate in the button click

want to know how to disable the validation that has happening immeadiately when you type in and when trying to edit it

I think you can remove the validator from field and implement it as a Binder level bean validator (Binder.withValidator)

(keep in mind this only works with read/write bean; not set)

@quirky-zebra good point! Thanks for pointing out

Cannot validate binder: bean level validators have been configured but no bean is currently set

        if (binder.isValid()) {
            Binder.Binding<Unit, String> unitNameValidator = binder.forField(unitName)
                    .withValidator(s -> checkUnitNameAlreadyExists(s), "Unit name already exists")
            if (binder.validate().getBeanValidationErrors().isEmpty()) {

            } else {

I found a solution in SO but the code is getting duplicated. This is what I’ve now and is working as expected.

but as you see here, I’m doing the binding twice. The one you see above is same binding done twice but with validator
any other way to achive this ?

I know that sounds probably to easy, but not all validations has to be done with the binder, you can always use the good old if(!condition) showError

I would just check isUnitNameExists with 2 parameters the name and the id. Then you can check it on the field. Or simply do it in the save() method like knoobie said.