Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JSF clear fields on validation errors

 
Rapsu Rapsinen
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JSF1.2 (JSF portlet)

The idea is to somehow clear all fields that have validation errors. This should work in a way that the request processing would always proceed to the UPDATE_MODEL_VALUES phase so that fields that passed would be committed to backing beans whereas failed fields would be set to empty values.

Example:
1) There is a validator on a field that requires value greater then 10
2) User input 5 to the field
3) Form is submitted through action
4) Validator produces an error message and attaches it to the field, but will not throw ValidatorException.
5) Instead the corresponding backing bean value is cleared
6) Action is processed

Any ideas? How should I implement such a validator that would not throw exception but clear the backing bean value?


I've tried using:
public void validate(FacesContext context, UIComponent component,Object valueObject) throws ValidatorException {
...
((UIInput)component).setValue(null);
context.addMessage(clientId, message);

}


This works quite well, but fails to work with input fields inside htmldatatable. With htmlDataTable even if the component value is set to null, the backing bean value will be set accordingly to the original component value.








 
Tim Holloway
Saloon Keeper
Pie
Posts: 18277
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That isn't how JSF is designed. JSF expects that you will retain the input value and display a message that assists the user in correcting it. If the JSF validators flunk the value (in other words, declare it invalid) the action processor is never invoked - the JSF lifecycle short-circuits back to redisplaying the View with validation errors. The intent is that the JSF backing bean is never updated unless ALL submitted properties are valid.

If you want the kind of behavior you've described, you'll have to remove all validations from the View definition and validate them manually in your action processor. Of course, since this means that the backing bean will have been updated with all the invalid properties, you'll not only have to clear the ones you want cleared, it's also your responsibility to do whatever other cleanup is required so that bad data doesn't leak into the application.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic