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?
Empty submitted values default to empty strings, not
null. Instead, you need to check if the string is empty byString#isEmpty():You perhaps want to cover blank spaces as well. In that case, add
trim():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 checkString#length()instead.However, that’s not the normal way of required field validation. You should put the
required="true"attribute on the input field instead.This way JSF will validate it by itself and display the appropriate message and will skip the action method invocation.
See also: