Jsf trimming spaces

Hi

I have an input field in which I want to trim any leading / trailing spaces. We use JSF and bind the input field to bean support in jsp using:

<h:inputText id="inputSN" value="#{regBean.inputSN}" maxlength="10"/> 

My question is, besides checking, can this be done in jsp? I know that we can also do this using the java function trim () in the handler, but it's just interesting if there is a more elegant way to achieve this in JSF.

Thanks.

+7
jsf whitespace trimming
source share
4 answers

You can use Converter ( tutorial ).

+6
source share

As suggested by McDowell and BalusC, you can create a converter and register it using the @FacesConvert annotation for the String class. And then in the getAsObject method, check the type of UIComponent and apply trimming only to the HtmlInputText components.

 @FacesConverter(forClass = String.class) public class StringTrimConverter implements Serializable, javax.faces.convert.Converter { @Override public Object getAsObject(FacesContext context, UIComponent cmp, String value) { if (value != null && cmp instanceof HtmlInputText) { // trim the entered value in a HtmlInputText before doing validation/updating the model return value.trim(); } return value; } @Override public String getAsString(FacesContext context, UIComponent cmp, Object value) { if (value != null) { // return the value as is for presentation return value.toString(); } return null; } } 
+4
source share

I answered a similar question here

Basically, you can either create your own component, which is a copy of inputText that automatically trims, or you can extend the inputText attribute and add a trim attribute that trims true.

+2
source share

I solved this by simply using the trim () function in the handler before doing any processing. it just seemed the most direct way to do it.

+1
source share

All Articles