Form Validation in JSF
I got an email a couple of days ago with someone asking me about how to do form validation in JSF. I figured that might be a common interest so here is the exchange
The way I'd do what you suggest is to code the validation in a method and have that method invoked from the
action that will determine where to go next (like the submit).
// validation method
public boolean validateForm() {
// validate the form
// each field in the form typically has a field in this class
// where something is not valid add a message
// if everything is valid return true other wise return false
}
public String submit() {
boolean valid = validateForm();
String logicalOutcome = null;
if(valid) {
logicalOutcome = "next page";
} else {
// null will cause it to return to the same page
// since you added the messages in the validate method
// they will be available in your ui if you use <h:messages/>
logicalOutcome = null;
}
return logicalOutcome;
}
then in your faces config file (faces-config.xml typically) you'd have something like this
...
<navigation-rule>
<from-view-id>/firstPage.jsp</from-view-id>
<navigation-case>
<from-outcome>next page</from-outcome>
<to-view-id>/otherPage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
...
if the form is validated the navigation rule would take you to 'otherPage.jsp', if not since the return is null you'd stay on the same page and display error messages
Hope this helps!

