Why does <h:inputText required=“true”> allow blank spaces?

天大地大妈咪最大 提交于 2019-11-27 08:54:18

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!