15

When I set required="true" in a <h:inputText>, it still allows blank spaces. I have been trying to modify the jsf-api.jar but I could not understand how to generate new a JAR, so I tried to modify the isEmpty() method from UIInput class and compile it, open the jsf-api.jar and replace it with the new one, but it did not work.

What I need is to do trim() when the user writes in a <h:inputText> to do not allow blank spaces. How can I achieve this?

If you want to download the jsf-api.jar resource, you can do it, just read how to at: http://javaserverfaces.java.net/checkout.html.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ing.LkRuiZ
  • 262
  • 1
  • 3
  • 10

2 Answers2

44

That's normal and natural behaviour and not JSF specific. A blank space may be perfectly valid input. The required="true" only kicks in on empty inputs, not in filled inputs. In JSF you can however just create a Converter for String class to automatically trim the whitespace.

@FacesConverter(forClass=String.class)
public class StringTrimmer implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return value != null ? value.trim() : null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return (String) value;
    }

}

Put this class somewhere in your project. It'll be registered automatically thanks to @FacesConverter and invoked automatically for every String entry thanks to forClass=String.class.

No need to hack the JSF API/impl. This makes no sense.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • WoW!!! It was easy and it worked, thank you. I had spent many hours doing this task :/ – Ing.LkRuiZ Nov 30 '11 at 16:01
  • You're welcome. In the future, whenever you think "I need to hack JSF", first ask a quesiton here on Stack Overflow if your reason is really valid ;) – BalusC Nov 30 '11 at 16:03
  • 1
    Just a note: if this does not seem to work (the converter is never called), check the answers in [this question](http://stackoverflow.com/q/10214121/840977) – Louise Oct 05 '12 at 14:52
  • I am getting this exception : `java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String` – Akhil Feb 18 '15 at 07:05
9

If you want to turn off the behavior that BalusC notes as one of the answers as standard JSF behavior, you can modify the web.xml and include the following.

<context-param>
   <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
   <param-value>true</param-value>
<context-param>

This will trigger the JSF framework to consider the values null which may be preferable, or an alternative to the answer from BalusC.

John Yeary
  • 1,112
  • 22
  • 45
  • 2
    OP's concrete problem concerns strings with spaces/whitespace, not empty strings, for which this context param is indeed one of the solutions. – BalusC Dec 10 '12 at 18:53