为什么< h:inputText required ="true">允许空格? [英] Why does <h:inputText required="true"> allow blank spaces?
问题描述
当我在<h:inputText>
中设置required="true"
时,它仍然允许空格.我一直在尝试修改jsf-api.jar
,但是我不明白如何生成新的JAR,因此我尝试从UIInput
类修改isEmpty()
方法并进行编译,打开jsf-api.jar
并将其替换为新的,但是没有用.
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.
我需要做的是trim()
,当用户在<h:inputText>
中书写时不允许有空格.我该如何实现?
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?
如果要下载jsf-api.jar
资源,可以做到这一点,只需阅读以下方法即可: http://javaserverfaces.java.net/checkout.html .
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.
推荐答案
这是正常现象,不是JSF特有的.空格可能是完全有效的输入. required="true"
仅在空输入上跳动,在填充的输入上跳动.但是,在JSF中,您可以为String
类创建一个Converter
以自动修剪空白.
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;
}
}
将此课程放在您的项目中的某个位置.借助于@FacesConverter
,它会自动注册,并借助于forClass=String.class
,它会为每个String
条目自动调用.
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
.
不需要,可以入侵JSF API/impl.这是没有道理的.
No need to hack the JSF API/impl. This makes no sense.
这篇关于为什么< h:inputText required ="true">允许空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!