问题
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