jAstrologer JSF Tutorial - Custom Validation in the Backing Bean

Although performing validation using required fields and converters is easy, it is also very limited. The error messages are not formatted very nicely and the checking that you can perform is limited. We can acheive more fine-tuned validation and better display of errors by coding validation into our backing bean.

For example, the converter checks that the birthday field is a valid date, but it doesn't check that the date was in the past. We are now going to check for this case in our custom validation and list any errors at the top of the page in a bulleted list.

  1. Open UserBean.java and make the following changes in bold:
    public class UserBean {
        
        private String name = "";
        private Date birthday;
        private ArrayList errors = new ArrayList();
        
    	...
    	    
        public String getErrors() {
            String message;
            if (errors.size() == 0) {
                message = "";
            } else {
                message = "<FONT COLOR=RED><B><UL>\\n";
                for(int i=0; i<errors.size(); i++) {
                    message = message + "<LI>" +
                            (String)errors.get(i) + "\\n";
                }
                message = message + "</UL></B></FONT>\\n";
            }
            return(message);
        }
        
        public String submit() {
            if (birthday == null) {
                errors.add("Valid birthday required");
            }
            else if (birthday.getTime() > new Date().getTime()) {
                errors.add("Birthday must be some time in the past");
            }
            if (name == "") {
                errors.add("Name required");
            }
            if (errors.size() > 0) {
                return(null);
            } else {
                return("submit");
            }
        }    
        
    }
  2. Open greeting.jsp and make the following changes in bold:
        <f:view>
            <h:form>
                <h:outputText value="#{UserBean.errors}" escape="false"/>
                <p>Enter your name: <h:inputText value="#{UserBean.name}" /></p>
                <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" >
                    <f:convertDateTime pattern="dd/MM/yyyy" />
                </h:inputText> (dd/mm/yyyy)</p>
                <h:commandButton value="Submit" action="#{UserBean.submit}" />
            </h:form>
        </f:view>
  3. Run the project and click Submit without entering any data. You get the following error:

    nicely formatted errors

Comments:

Post a Comment:
Comments are closed for this entry.
About

johnc

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today