为什么 <h:inputText required="true">允许空格? [英] Why does <h:inputText required="true"> allow blank spaces?

查看:21
本文介绍了为什么 <h:inputText required="true">允许空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 中设置 required="true" 时,它仍然允许空格.我一直在尝试修改 jsf-api.jar 但我无法理解如何生成新的 JAR,所以我尝试修改 isEmpty() 方法从 UIInput 类并编译,打开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() 当用户在 中写入时不允许空格.我怎样才能做到这一点?

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.

这篇关于为什么 &lt;h:inputText required="true"&gt;允许空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆