Skip to content

Commit e606d94

Browse files
authored
feat: enable components to notify binder when validation state changes (#13940) (CP: 23.1) (#13993)
Adds the needed API to notify Binder about validation status changes that happen in field components. Fixes #8242 Related to vaadin/flow-components#1158
1 parent 00791b2 commit e606d94

6 files changed

Lines changed: 405 additions & 0 deletions

File tree

‎flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,11 @@ public interface BindingBuilder<BEAN, TARGET> extends Serializable {
318318
* If the Binder is already bound to some bean, the newly bound field is
319319
* associated with the corresponding bean property as described above.
320320
* <p>
321+
* If the bound field implements {@link HasValidator}, then the binding
322+
* instance returned by this method will subscribe for field's
323+
* {@code ValidationStatusChangeEvent}s and will {@code validate} itself
324+
* upon receiving them.
325+
* <p>
321326
* The getter and setter can be arbitrary functions, for instance
322327
* implementing user-defined conversion or validation. However, in the
323328
* most basic use case you can simply pass a pair of method references
@@ -966,6 +971,12 @@ public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
966971
}
967972
this.binding = binding;
968973

974+
if (field instanceof HasValidator) {
975+
HasValidator<FIELDVALUE> hasValidatorField = (HasValidator<FIELDVALUE>) field;
976+
hasValidatorField.addValidationStatusChangeListener(
977+
event -> this.binding.validate());
978+
}
979+
969980
return binding;
970981
}
971982

‎flow-data/src/main/java/com/vaadin/flow/data/binder/HasValidator.java‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717

1818
import java.io.Serializable;
1919

20+
import com.vaadin.flow.function.ValueProvider;
21+
import com.vaadin.flow.shared.Registration;
22+
2023
/**
2124
* A generic interface for field components and other user interface objects
2225
* that have a user-editable value that should be validated.
@@ -41,4 +44,89 @@ public interface HasValidator<V> extends Serializable {
4144
default Validator<V> getDefaultValidator() {
4245
return Validator.alwaysPass();
4346
}
47+
48+
/**
49+
* Enables the implementing components to notify changes in their validation
50+
* status to the observers.
51+
* <p>
52+
* <strong>Note:</strong> This method can be overridden by the implementing
53+
* classes e.g. components, to enable the associated {@link Binder.Binding}
54+
* instance subscribing for their validation change events and revalidate
55+
* itself.
56+
* <p>
57+
* This method primarily designed for notifying the Binding about the
58+
* validation status changes of a bound component at the client-side.
59+
* WebComponents such as <code>&lt;vaadin-date-picker&gt;</code> or any
60+
* other component that accept a formatted text as input should be able to
61+
* communicate their invalid status to their server-side instance, and a
62+
* bound server-side component instance must notify its binding about this
63+
* validation status change as well. When the binding instance revalidates,
64+
* a chain of validators and convertors get executed one of which is the
65+
* default validator provided by {@link HasValidator#getDefaultValidator()}.
66+
* Thus, In order for the binding to be able to show/clear errors for its
67+
* associated bound field, it is important that implementing components take
68+
* that validation status into account while implementing any validator and
69+
* converter including {@link HasValidator#getDefaultValidator()}. Here is
70+
* an example:
71+
*
72+
* <pre>
73+
* &#64;Tag("date-picker-demo")
74+
* public class DatePickerDemo implements HasValidator&lt;LocalDate&gt; {
75+
*
76+
* boolean clientSideValid = true;
77+
*
78+
* /**
79+
* * Note how <code>clientSideValid</code> engaged in the definition
80+
* * of this method. It is important to reflect this status either
81+
* * in the returning validation result of this method or any other
82+
* * validation that is associated with this component.
83+
* *&#47;
84+
* &#64;Override
85+
* public Validator getDefaultValidator() {
86+
* return clientSideValid ? ValidationResult.ok()
87+
* : ValidationResult.error("Invalid date format");
88+
* }
89+
*
90+
* private final Collection&lt;ValidationStatusChangeListener&lt;LocalDate&gt;&gt;
91+
* validationStatusListeners = new ArrayList&lt;&gt;();
92+
*
93+
* /**
94+
* * This enables the binding to subscribe for the validation status
95+
* * change events that are fired by this component and revalidate
96+
* * itself respectively.
97+
* *&#47;
98+
* &#64;Override
99+
* public Registration addValidationStatusChangeListener(
100+
* ValidationStatusChangeListener&lt;LocalDate&gt; listener) {
101+
* validationStatusListeners.add(listener);
102+
* return () -&gt; validationStatusListeners.remove(listener);
103+
* }
104+
*
105+
* // Each web-component has a way to communicate its validation status
106+
* // to its server-side component instance which can update
107+
* // <code>this.clientSideValid</code> state.
108+
*
109+
* private void fireValidationStatusChangeEvent(
110+
* boolean newValidationStatus) {
111+
* if (this.clientSideValid != newValidationStatus) {
112+
* this.clientSideValid = newValidationStatus;
113+
* var event = new ValidationStatusChangeEvent&lt;&gt;(this,
114+
* newValidationStatus);
115+
* validationStatusListeners.forEach(
116+
* listener -&gt; listener.validationStatusChanged(event));
117+
* }
118+
* }
119+
* }
120+
* </pre>
121+
*
122+
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
123+
* Setter)
124+
* @since 2.7
125+
*
126+
* @return Registration of the added listener.
127+
*/
128+
default Registration addValidationStatusChangeListener(
129+
ValidationStatusChangeListener<V> listener) {
130+
return null;
131+
}
44132
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.data.binder;
17+
18+
import com.vaadin.flow.component.HasValue;
19+
20+
import java.io.Serializable;
21+
22+
/**
23+
* The event to be processed when
24+
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
25+
* invoked.
26+
*
27+
* @since 2.7
28+
*
29+
* @param <V>
30+
* the value type
31+
*/
32+
public class ValidationStatusChangeEvent<V> implements Serializable {
33+
34+
private final HasValue<?, V> source;
35+
private final boolean newStatus;
36+
37+
public ValidationStatusChangeEvent(HasValue<?, V> source,
38+
boolean newStatus) {
39+
this.source = source;
40+
this.newStatus = newStatus;
41+
}
42+
43+
public HasValue<?, V> getSource() {
44+
return source;
45+
}
46+
47+
public boolean getNewStatus() {
48+
return newStatus;
49+
}
50+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.data.binder;
17+
18+
import java.io.Serializable;
19+
20+
import com.vaadin.flow.function.ValueProvider;
21+
22+
/**
23+
* The listener interface for receiving {@link ValidationStatusChangeEvent}
24+
* events. The classes that are interested in processing validation status
25+
* changed events of field components should register implementation of this
26+
* interface via
27+
* {@link HasValidator#addValidationStatusChangeListener(ValidationStatusChangeListener)}
28+
* which are called whenever such event is fired by the component.
29+
* <p>
30+
* This interface is primarily introduced to enable binding instances subscribe
31+
* for their own associated field's validation status change events and
32+
* revalidate after that. However, when all the components implementing
33+
* {@code HasValidator} interface, implement the correct behaviour for adding
34+
* and notifying listeners of the current type, other usages are also become
35+
* possible since the {@link ValidationStatusChangeEvent} payload contains the
36+
* source {@link com.vaadin.flow.component.HasValue} field and the new
37+
* validation status, thus for instance fields or buttons in a view can
38+
* subscribe for each other's validation statuses and enable/disable or clear
39+
* values, etc. respectively.
40+
*
41+
* @since 2.7
42+
*
43+
* @see HasValidator
44+
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
45+
* Setter)
46+
*/
47+
@FunctionalInterface
48+
public interface ValidationStatusChangeListener<V> extends Serializable {
49+
50+
/**
51+
* Invoked when a ValidationStatusChangeEvent occurs.
52+
*
53+
* @param event
54+
* the event to be processed
55+
*/
56+
void validationStatusChanged(ValidationStatusChangeEvent<V> event);
57+
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package com.vaadin.flow.data.binder;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
import org.junit.Assert;
7+
import org.junit.Before;
8+
import org.junit.Test;
9+
import org.mockito.Mockito;
10+
11+
import com.vaadin.flow.data.binder.testcomponents.TestHasValidatorDatePicker;
12+
import com.vaadin.flow.component.HasValue;
13+
import com.vaadin.flow.tests.data.bean.Person;
14+
15+
import static com.vaadin.flow.data.binder.testcomponents.TestHasValidatorDatePicker.INVALID_DATE_FORMAT;
16+
17+
public class BinderValidationStatusChangeListenerTest
18+
extends BinderTestBase<Binder<Person>, Person> {
19+
20+
private static final String BIRTH_DATE_PROPERTY = "birthDate";
21+
22+
private final Map<HasValue<?, ?>, String> componentErrors = new HashMap<>();
23+
24+
@Before
25+
public void setUp() {
26+
binder = new Binder<>(Person.class) {
27+
@Override
28+
protected void handleError(HasValue<?, ?> field,
29+
ValidationResult result) {
30+
componentErrors.put(field, result.getErrorMessage());
31+
}
32+
33+
@Override
34+
protected void clearError(HasValue<?, ?> field) {
35+
super.clearError(field);
36+
componentErrors.remove(field);
37+
}
38+
};
39+
item = new Person();
40+
}
41+
42+
@Test
43+
public void fieldWithHasValidatorDefaults_bindIsCalled_addValidationStatusListenerIsCalled() {
44+
var field = Mockito.spy(
45+
TestHasValidatorDatePicker.DatePickerHasValidatorDefaults.class);
46+
binder.bind(field, BIRTH_DATE_PROPERTY);
47+
Mockito.verify(field, Mockito.times(1))
48+
.addValidationStatusChangeListener(Mockito.any());
49+
}
50+
51+
@Test
52+
public void fieldWithHasValidatorOnlyGetDefaultValidatorOverridden_bindIsCalled_addValidationStatusListenerIsCalled() {
53+
var field = Mockito.spy(
54+
TestHasValidatorDatePicker.DataPickerHasValidatorGetDefaultValidatorOverridden.class);
55+
binder.bind(field, BIRTH_DATE_PROPERTY);
56+
Mockito.verify(field, Mockito.times(1))
57+
.addValidationStatusChangeListener(Mockito.any());
58+
}
59+
60+
@Test
61+
public void fieldWithHasValidatorOnlyAddListenerOverridden_bindIsCalled_addValidationStatusListenerIsCalled() {
62+
var field = Mockito.spy(
63+
TestHasValidatorDatePicker.DataPickerHasValidatorAddListenerOverridden.class);
64+
binder.bind(field, BIRTH_DATE_PROPERTY);
65+
Mockito.verify(field, Mockito.times(1))
66+
.addValidationStatusChangeListener(Mockito.any());
67+
}
68+
69+
@Test
70+
public void fieldWithHasValidatorFullyOverridden_bindIsCalled_addValidationStatusChangeListenerIsCalled() {
71+
var field = Mockito.spy(
72+
TestHasValidatorDatePicker.DataPickerHasValidatorOverridden.class);
73+
binder.bind(field, BIRTH_DATE_PROPERTY);
74+
Mockito.verify(field, Mockito.times(1))
75+
.addValidationStatusChangeListener(Mockito.any());
76+
}
77+
78+
@Test
79+
public void fieldWithHasValidatorFullyOverridden_fieldValidationStatusChangesToFalse_binderHandleErrorIsCalled() {
80+
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorOverridden();
81+
binder.bind(field, BIRTH_DATE_PROPERTY);
82+
Assert.assertEquals(0, componentErrors.size());
83+
84+
field.fireValidationStatusChangeEvent(false);
85+
Assert.assertEquals(1, componentErrors.size());
86+
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));
87+
}
88+
89+
@Test
90+
public void fieldWithHasValidatorFullyOverridden_fieldValidationStatusChangesToTrue_binderClearErrorIsCalled() {
91+
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorOverridden();
92+
binder.bind(field, BIRTH_DATE_PROPERTY);
93+
Assert.assertEquals(0, componentErrors.size());
94+
95+
field.fireValidationStatusChangeEvent(false);
96+
Assert.assertEquals(1, componentErrors.size());
97+
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));
98+
99+
field.fireValidationStatusChangeEvent(true);
100+
Assert.assertEquals(0, componentErrors.size());
101+
Assert.assertNull(componentErrors.get(field));
102+
}
103+
104+
@Test
105+
public void fieldWithHasValidatorOnlyAddListenerOverriddenAndCustomValidation_fieldValidationStatusChangesToFalse_binderHandleErrorIsCalled() {
106+
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorAddListenerOverridden();
107+
binder.forField(field).withValidator(field::customValidation)
108+
.bind(BIRTH_DATE_PROPERTY);
109+
110+
field.fireValidationStatusChangeEvent(false);
111+
Assert.assertEquals(1, componentErrors.size());
112+
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));
113+
}
114+
115+
@Test
116+
public void fieldWithHasValidatorOnlyAddListenerOverriddenAndCustomValidation_fieldValidationStatusChangesToTrue_binderClearErrorIsCalled() {
117+
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorAddListenerOverridden();
118+
binder.forField(field).withValidator(field::customValidation)
119+
.bind(BIRTH_DATE_PROPERTY);
120+
121+
field.fireValidationStatusChangeEvent(false);
122+
Assert.assertEquals(1, componentErrors.size());
123+
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));
124+
125+
field.fireValidationStatusChangeEvent(true);
126+
Assert.assertEquals(0, componentErrors.size());
127+
Assert.assertNull(componentErrors.get(field));
128+
}
129+
130+
}

0 commit comments

Comments
 (0)