This question follows on from my earlier one, Inline validation using JSR-303 in GWT, part 1: Validation on TextBox fails. Why? in which I describe a failed first attempt to use JSR-303 for inline validation, and ask for help in understanding why it didn't work.
The main documentation I'm using is the GWT validation dev guide and JSR-303 spec.
My second attempt moves the constraint definitions into an interface:
import javax.validation.constraints.Pattern;
public interface FooValidation {
@Pattern(regexp="^[0-9]+$", message="Foo: expected digits.")
public String getFoo();
}
MyValidatorFactory
now specifies that the FooValidation
interface is to be validated
@GwtValidation(FooValidation.class)
public interface GwtValidator extends Validator {
}
and my TextBox
implements the interface in which the JSR-303 constraints are defined:
public class FooWidget extends TextBox implements FooValidation {
public String getFoo() {
return getValue(); // from TextBox
}
}
The field is placed in the form using UiBinder
:
<my:FooWidget ui:field="foo"></my:FooWidget>
and included in my form widget in the usual way:
@UiField
FooWidget foo;
The constraints can then be checked onBlur, for example:
@UiHandler("foo")
void onBlur(BlurEvent ev) {
// Need to cast (code smell?) to FooValidation,
// because that is the class set up for validations
Set<ConstraintViolation<FooValidation>> violations =
validator.validate((FooValidation)foo);
for (ConstraintViolation<FooValidation> violation : violations) {
// TODO - report violation.getMessage() to user
}
}
Now, this seems to work (based on very limited smoke testing, yesterday!).
But the approach feels a bit laboured.
I've introduced two new 'artefacts' (FooWidget
and FooValidation
) just to service the validation mechanism,
which goes against the cut of Occam's Razor!
Am I missing something simpler?
Before I go ahead and implement a load of validations using this pattern, I'd be very interested to learn of any pitfalls,
and of other people's experience using JSR-303 for inline validation in GWT.
I expect I can refine the above approach, and tease out some general purpose abstractions, but it would be good to know if I've missed something before continuing along that path.