Add validation after binding the field

Hi all,

is it possible to add a validator to a binder after the field is binded for instance like this?

Binder binder = new Binder<>(MyFormData.class);

Binder.Binding fieldBinded = binder.forField(myBigDecimalField)
.bind(MyFormData::getMyBigDecimal, MyFormData::setMyBigDecimal);

fieldBinded.setAsRequired(“The field il mandatory”)

Thanks

Is it because you want the field be required based on some condition?

yes

but i also need to add other validations based on conditions

Something like this maybe?

var binded = binder.forField(text2Field)
                .asRequired("This field is mandatory") // initially required (otherwise didn't work for me)
                .bind(Data::getText2, Data::setText2);
...
binded.setAsRequiredEnabled(false); // if you want it initially not required
...
// change field requirement based on checkbox value change
shouldBeRequiredCheckbox.addValueChangeListener(change-> {
    binded.setAsRequiredEnabled(change.getValue());
    binded.validate(); 
});

@incredible-wolf thanks for your sample, is very useful for required validation.

is it possible to add and manage also some other validations like BigDecimalRangeValidator in the same way?

Thanks

You either create your own validator which has some advanced logic or you have to unbind the binding and create a new one for that field

thanks @quirky-zebra @incredible-wolf, i just did it with some extra code.

Thanks

Hello, We used custom “ControlableValidator” approach. It wraps inside one or more Validators. This validator is then bound to the feature. It also has API setEnabled(true/false) which controls if the wrapped validators are used or not. It’s kind a workaround but it works well :slightly_smiling_face: