How to validate an empty field in action method?

[亡魂溺海] 提交于 2019-12-24 08:51:26

问题


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|#]

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?


回答1:


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.
}

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.
}

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.
}

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" />

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

See also:

  • Debug JSF lifecycle


来源:https://stackoverflow.com/questions/8183353/how-to-validate-an-empty-field-in-action-method

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