JSF trimming white spaces

16,149

Solution 1

You could use a Converter (tutorial).

Solution 2

As suggested by McDowell and BalusC, you can create a Converter, and register it with @FacesConvert annotation for the String class. And then in the getAsObject method check the UIComponent type and apply the trimming only for 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;
    }

}

Solution 3

I answered a similar question here

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

Solution 4

I resolved this by just using the trim() function in the handler before doing any processing. it just seemed like the most straight forward way of doing this.

Share:
16,149
msharma
Author by

msharma

Updated on June 04, 2022

Comments

  • msharma
    msharma about 2 years

    HI,

    I have an input field in which I want to trim any leading/trailing whitespaces. We are using JSF and binding the input field to a backing bean in the jsp using:

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

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

    Thanks.

  • BalusC
    BalusC over 14 years
    And register it with converter-for-class for java.lang.String so that you don't need to define it on every UIInput component.
  • McDowell
    McDowell over 14 years
    @Martlark - it is an element used in faces-config.xml. From spec: /faces-config/converter -- Create or replace a converter id/converter class or target class/converter class pair with the Application instance for this web application. Also: The “converter-for-class” element represents the fully qualified class name for which a Converter class will be registered. See the JSF specification for more.
  • Jasper de Vries
    Jasper de Vries over 6 years
    Or, if you don't feel like coding it yourself, see showcase.omnifaces.org/converters/TrimConverter
  • Kawu
    Kawu over 4 years
    I personally feel THE ABOVE COMMENT should be the accepted answer