Sunday, January 12, 2014

Re: Displaying validation errors ?

Hello.


> when validating user input, each ui control that holds a faulty value
> should signal this by displaying a red border or something like this.
> Alternatively a list with all errors should be displayed on top of the page
> like "Field '<name_of_control_a>' must not be empty", "Field
> '<name_of_control_b>' only accepts numbers" and so on.
> With bean validation, a pojo field must not refer directly to an ui control
> value. But if so, how to extract the information from the error messages
> which ui control belongs to a particular message? You can do this by hand.
> But there should be some automatism.


The Editor framework
http://www.gwtproject.org/doc/latest/DevGuideUiEditors.html combined with the
Validation framework
http://www.gwtproject.org/doc/latest/DevGuideValidation.html should give a
good start.


If the controls you use are ValueBoxEditorDecorator or implement
HasEditorError (or other types, not sure of the full list), they can display
errors for their fields as reported from the Validation framework.


Assuming you got a Driver (here called "fieldBinder") for the field binding, you
can do the following to validate your input and report back to the user (Data
is your POJO class with validation):


final Data data = fieldBinder.flush();
Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Data>> violations = validator.validate(data);
final Set<?> convert = violations;
// errors will link to their correct field
fieldBinder.setConstraintViolations((Set<ConstraintViolation<?>>) convert);
if (!violations.isEmpty()) {
Window.scrollTo(0, 0);
final StringBuffer error = new StringBuffer();
String sep = "";
for (final ConstraintViolation<Data> violation : violations) {
if ("".equals(violation.getPropertyPath().toString())) {
error.append(violation.getMessage()).append(sep);
sep = " ; ";
}
}
if (error.length() > 0) {
showError(error.toString());
}
return;
}


Two notes on that code:
- you need to use the Set<ConstraintViolation> for some obscure reason I don't
remember (not totally compatible types?)

- the loop on violations only takes errors without any path, to display them
on top of the dialog ; those errors are created by my custom validation class
and are not linked to a specific field (ie "if you check that option, please fill
this field")



The ValueBoxEditorDecorator will I think put the error on the left of the
control, but you can use CSS to display it on the right (or maybe you can
override its template). And you should be able to implement your own class to
underline the invalid control.



Hope this helps


Regards


Nicolas

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate