如何验证操作方法中的空字段? [英] How to validate an empty field in action method?

查看:132
本文介绍了如何验证操作方法中的空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段和一个按钮.我想在执行按钮操作之前检查textinput是否有效.如果有效,我将呈现一条响应消息.我有这样的代码:

I have an input field and a button. I want to check if the textinput is valid before executing the button action. If it is valid I will render a response message. I have a code like this:

public void submitReportRequest() {
    if(nameField!=null){
        System.out.println("aaaaaaaaaaaaa");
        submitted=true;
    }
    if(nameField == null){
        System.out.println("report name is null!!!!!!");
    }
}

但是从控制台我只能得到:

but from the console I just get:

[#|2011-11-18T15:22:49.931+0200|INFO|glassfishv3.0|null|_ThreadID=21;_ThreadName=Thread-1;|aaaaaaaaaaaaa|#]

nameField为空时,在控制台中我什么也没收到,只是页面重新显示了nameField的验证消息.我从JSF生命周期知道,如果验证阶段失败,那么它会直接跳到渲染响应阶段,并且永远不会达到按钮操作.但是在这种情况下如何实现我的目标?

when the nameField is empty, I receive nothing in the console just page is re-rendered with the validation message of nameField. I know from the JSF life cycle if the validation phase fails then it jumps directly to the render response phase and button action is never reached. But how can I achieve my objective in this case?

推荐答案

空的提交值默认为空字符串,而不是null.相反,您需要通过 String#isEmpty() :

Empty submitted values default to empty strings, not null. Instead, you need to check if the string is empty by String#isEmpty():

if (nameField.isEmpty()) {
    // Name field is empty.
} else {
    // Name field is not empty.
}

您也许还希望覆盖空白.在这种情况下,请添加trim():

You perhaps want to cover blank spaces as well. In that case, add trim():

if (nameField.trim().isEmpty()) {
    // Name field is empty or contained spaces only.
} else {
    // Name field is not empty and did not contain spaces only.
}

请注意,String#isEmpty()是Java 1.6中引入的.如果由于某种原因仍使用Java 1.5或更高版本,则需要检查

Note that the String#isEmpty() is introduced in Java 1.6. If you're still on Java 1.5 or older for some reason, then you need to check String#length() instead.

if (nameField.length() == 0) {
    // Name field is empty.
} else {
    // Name field is not empty.
}

但是,这不是必需的字段验证的常规方法.您应该在输入字段上放置required="true"属性.

However, that's not the normal way of required field validation. You should put the required="true" attribute on the input field instead.

<h:inputText id="name" value="#{bean.name}" required="true" />
<h:message for="name" />

通过这种方式,JSF将自行对其进行验证并显示适当的消息,并跳过操作方法的调用.

This way JSF will validate it by itself and display the appropriate message and will skip the action method invocation.

这篇关于如何验证操作方法中的空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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