Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Validation Using Validator JSF Components and Custom Validators

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - JavaServer™ Faces Web Applications

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Validation Using Validator JSF Components and Custom Validators

This section introduces form validation. Validating user input is an important step in collecting information from users.

Validation Using Validator Components and Custom Validators


This section introduces form validation. Validating user input is an important step in collecting information from users. Validation helps prevent processing errors due to incom-plete or improperly formatted user input. For example, you may perform validation to ensure that all required fields have been filled out or that a zip-code field contains exactly five digits. Netbeans provides three validator components. A Length Validator determines whether a field contains an acceptable number of characters. Double Range Validators and Long Range Validators determine whether numeric input falls within acceptable ranges. Package javax.faces.validators contains the classes for these validators. Netbeans also allows custom validation with validator methods in the page bean file. The following ex-ample demonstrates validation using both a validator component and custom validation.


Validating Form Data in a Web Application

The example in this section prompts the user to enter a name, e-mail address and phone number. After the user enters any data, but before the data is sent to the web server, vali-dation ensures that the user entered a value in each field, that the entered name does not exceed 30 characters, and that the e-mail address and phone number values are in an ac-ceptable format. If the client does not have JavaScript enabled, then the validation would be performed on the server. In this example, (555) 123-4567, 555-123-4567 and 123-4567 are all considered valid phone numbers. Once the data is submitted, the web server responds by displaying an appropriate message and a Grid Panel component repeating the submitted information. Note that a real business application would typically store the sub-mitted data in a database or in a file on the server. We simply send the data back to the page to demonstrate that the server received the data.


Building the Web Page

This web application introduces two additional JSF components—Label and Message from the Basic section of the Palette. Each of the page’s three text fields should have its own label and message. Label components describe other components and can be associ-ated with user input fields by setting their for property. Message components display er-ror messages when validation fails. This page requires three Text Fields, three Labels and three Messages, as well as a submit Button. To associate the Label components and Mes-sage components with their corresponding Text Field components, hold the Ctrl and Shift keys, then drag the label or message to the appropriate Text Field. In the Properties win-dow, notice that each Label and Message component’s for property is set to the appropriate Text Field.

You should also add a Static Text component to display a validation success messageat the bottom of the page. Set the text to "Thank you for your submission.<br/>We received the following information:" and change the component’s id to resultText.


In the Properties window, unset the component’s rendered and escaped properties. The rendered property controls whether the component will be displayed the first time the page loads. Setting escaped to false enables the browser to recognize the <br/> tag so it can start a new line of text rather than display the characters "<br/>" in the web page.


Finally, add a Grid Panel component below the resultText component. The panel should have two columns, one for displaying Static Text components that label the user’s validated data, and one for displaying Static Text components that echo back that data. The panel’s rendered property should be set to false so that it is not initialially displayed.


The JSP file for this page is displayed in Fig. 26.15. Lines 34–40, 48–52 and 60–64 define webuijsf:textFields for retrieving the user’s name, e-mail address and phone number, respectively. Lines 31–33, 45–47 and 57–59 define webuijsf:labels for each of these text fields. Lines 41–44, 53–56 and 65–68 define the text fields’ webuijsf:message elements. Lines 69–73 define a Submit webuijsf:button. Lines 74–78 create a webuijsf:staticText named resultText that displays the response from the server when the user successfully submits the form, and lines 79–99 define a webuijsf:panelGrid that contains components for echoing validated user input to the browser.


1  <?xml version = "1.0" encoding = "UTF-8"?>



116             <!-- Fig. 26.15: Validation.jsp -->


117 <!-- JSP that demonstrates validation of user input. -->


118 <jsp:root version = "1.2"


119   xmlns:f = "http://java.sun.com/jsf/core"


120   xmlns:h = "http://java.sun.com/jsf/html"


121   xmlns:jsp = "http://java.sun.com/JSP/Page"


122   xmlns:webuijsf = "http://www.sun.com/webui/webuijsf">


123     <jsp:directive.page contentType = "text/html;charset=UTF-8"


124            pageEncoding = "UTF-8"/>


125     <f:view>


126     <webuijsf:page binding = "#{Validation.page1}" id = "page1">


127            <webuijsf:html binding = "#{Validation.html1}" id = "html1">


<webuijsf:head binding = "#{Validation.head1}" id = "head1">

16        <webuijsf:link binding = "#{Validation.link1}" id = "link1"

17        url = "/resources/stylesheet.css"/>

18        </webuijsf:head>


19        <webuijsf:body binding = "#{Validation.body1}" id = "body1"



20        style = "-rave-layout: grid">

21        <webuijsf:form binding = "#{Validation.form1}" id = "form1">

22        <webuijsf:staticText binding = "#{Validation.headerText}"

23        id = "headerText"     style = "font-size: 14px; font-weight:

24        bold; left: 24px;         top: 24px; position: absolute"

25        text = "Please fill out the following form:"/>

26        <webuijsf:staticText binding =

27        "#{Validation.instructionText}" id = "instructionText"

28        style = "font-size: 12px; font-style: italic; left:

29                    24px; top: 48px; position: absolute" text = "All fields

30                    are required and must contain valid information."/>

31        <webuijsf:label binding = "#{Validation.nameLabel}" for =

32                    "nameTextField" id = "nameLabel" style = "left: 24px;

33                    top: 75px; position: absolute" text = "Name:"/>              

34        <webuijsf:textField binding = "#{Validation.nameTextField}"

35                    id = "nameTextField" required = "true" style = "left:

36                    96px; top: 72px; position: absolute; width: 216px"

37                    validatorExpression =                                

38                    "#{Validation.nameLengthValidator.validate}"                          

39                    valueChangeListenerExpression =                    

40                    "#{Validation.nameTextField_processValueChange}"/>

41        <webuijsf:message binding = "#{Validation.nameMessage}"

42                    for = "nameTextField" id = "nameMessage" showDetail =

43                    "false" showSummary = "true"                 

44                    style = "left: 336px; top: 74px; position: absolute"/>

45        <webuijsf:label binding = "#{Validation.emailLabel}" for =

46                    "emailTextField" id = "emailLabel" style = "left: 24px;

47                    top: 109px; position: absolute" text = "E-Mail:"/>

48        <webuijsf:textField binding =                    

49                    "#{Validation.emailTextField}" id = "emailTextField"

50                    required = "true" style = "left: 96px; top: 106px;

51                    position: absolute; width: 216px"  validatorExpression =        

52                    "#{Validation.emailTextField_validate}"   />                    

53        <webuijsf:message binding = "#{Validation.emailMessage}"

54                    for = "emailTextField" id = "emailMessage" showDetail =

55                    "false" showSummary = "true" style = "left: 336px; top:

56                    108px; position: absolute"/>                      

57        <webuijsf:label binding = "#{Validation.phoneLabel}" for =

58                    "phoneTextField" id = "phoneLabel" style = "left: 24px;

59                    top: 143px; position: absolute" text = "Phone:"/>

60        <webuijsf:textField binding =                    

61                    "#{Validation.phoneTextField}" id = "phoneTextField"

62                    required = "true" style = "left: 96px; top: 140px;

63                    position: absolute; width: 216px"  validatorExpression =        

64                    "#{Validation.phoneTextField_validate}" />                    

65        <webuijsf:message binding = "#{Validation.phoneMessage}"

66                    for = "phoneTextField" id = "phoneMessage" showDetail =

67                    "false" showSummary = "true" style = "left: 336px; top:

68                    142px; position: absolute"/>                      

69        <webuijsf:button      actionExpression =                                     

70                    "#{Validation.submitButton_action}"        binding =                  

71        "#{Validation.submitButton}" id = "submitButton" style =

72                    "left: 23px; top: 192px; position: absolute; width:

73                    100px" text = "Submit"/>                

74        <webuijsf:staticText binding = "#{Validation.resultText}"

75                    escape = "false" id = "resultText" rendered = "false"

76                    style = "left: 24px; top: 216px; position: absolute"

77                    text = "Thank you for your submission.&lt;br/&gt;We

78                    received the following information:"/>                

79        <h:panelGrid binding = "#{Validation.resultGridPanel}"

80                    columns = "2" id = "resultGridPanel" rendered = "false"

81                    style = "border-width: 1px; border-style: solid;                

82        background-color: #ffff99; height: 96px; left: 24px;

83        top: 264px; position: absolute" width = "288">

84        <webuijsf:staticText binding =

85        "#{Validation.nameResultLabel}"

86        id = "nameResultLabel" text = "Name:"/>

87        <webuijsf:staticText binding =

88        "#{Validation.nameResult}" id = "nameResult"/>

89        <webuijsf:staticText binding =

90        "#{Validation.emailResultLabel}"

91        id = "emailResultLabel" text = "E-Mail:"/>

92        <webuijsf:staticText binding =

93        "#{Validation.emailResult}" id = "emailResult"/>

94        <webuijsf:staticText binding =

95        "#{Validation.phoneResultLabel}"

96        id = "phoneResultLabel" text = "Phone:"/>

97        <webuijsf:staticText binding =

98        "#{Validation.phoneResult}" id = "phoneResult"/>

99        </h:panelGrid>

100     </webuijsf:form>


101     </webuijsf:body>


102     </webuijsf:html>


103     </webuijsf:page>


104     </f:view>


105     </jsp:root>

Fig. 26.15 | JSP that demonstrates validation of user input.


Setting the Required Property of an Input Component

Ensuring that the user has made a selection or entered some text in a required input ele-ment is a basic type of validation. This is accomplished by checking the required box in the element’s Properties window. If you add a validator component or custom validator method to an input field, the field’s required property must be set to true for validation to occur. Notice that each of the three input webuijsf:textFields in this example has its required property set to true. Also note in the Visual Editor that the label for a required field is automatically marked by a red asterisk. If a user submits this form with empty text fields, the default error message for a required field will be displayed in the empty field’s associated webuijsf:message component. To customize the error message, you must pro-vide a custom validator.

Using the LengthValidator Component


In this example, we use the Length Validator component (found in the Validators section of the Palette) to ensure that the length of the user’s name does not exceed 30 characters. This might be useful to ensure that a value will fit in a particular database field.


To add a Length Validator to a component, simply drag the validator from the Palette and drop it onto the field to validate. A lengthValidator1 node will appear in the Outline window. To edit the validation component’s properties, click this node and set the max-imum and minimum properties to the desired number of characters in the Properties window. Here, we set only the maximum property to 30. We also changed the component’s

id to nameLengthValidator. Notice that the nameTextField’s validationExpression property has been bound to the nameLengthValidator’s validate method in the page bean file (lines 37–38). Remember that most client-side validation can be circumvented, so important validation should always be performed on the server.


This validator allows users to type as much text in the field as they wish, and if they exceed the limit, the default length validation error message will be displayed in the field’s webuijsf:message component after the user clicks the Submit button. It is possible to limit the length of user input without using validation. By setting a Text Field’s maxLength property, the Text Field’s cursor will not advance beyond the maximum allowable number of characters, so the user cannot submit data that exceeds the length limit.


Using Regular Expressions to Perform Custom Validation

Some of the most common validation tasks involve checking user input for appropriate formatting. For instance, it may be necessary to check user-entered e-mail addresses and telephone numbers to ensure that they conform to the standard formatting for valid e-mail addresses and phone numbers. Matching user input against a regular expression is an ef-fective way to ensure that the input is properly formatted. Netbeans does not provide com-ponents for validation using regular expressions, so we will add our own custom validator methods to the page bean file. To add a custom validator to an input component, right click the component and select Edit Event Handler > validate. This creates a validation method for the component with an empty body in the page bean file. We’ll add code to this method shortly. Note that both emailTextField and phoneTextField’s validate attributes are bound to their respective custom validation methods in the page bean file (lines 51–52 and 63–64).


Examining the Page Bean File for a Form That Receives User Input

Figure 26.16 contains the page bean file for the JSP file in Fig. 26.15. Line 31 sets the maximum length for the nameLengthValidator, which is a property of this page bean. Re-call that the name text field was bound to this property in the JSP file. Method emailTextField_validate (lines 410–422) and phoneTextField_validate (lines 426–438) are the custom validator methods that verify the user-entered e-mail address and phone number, respectively. The submitButton_action method (lines 441–452) echoes the data back to the user if validation succeeds. The validator methods are called before the event handler, so if validation fails, submitButton_action will not be called and the user input will not be echoed.


The two custom validator methods in this page bean file validate a text field’s contents against a regular expression using the String method match, which takes a regular expres-sion as an argument and returns true if the String conforms to the specified format.


5    // Fig. 26.16: Validation.java


6    // Validating user input.


7    package validation;


19 import com.sun.rave.web.ui.appbase.AbstractPageBean;


20 import com.sun.webui.jsf.component.Body;


21 import com.sun.webui.jsf.component.Button;


22 import com.sun.webui.jsf.component.Form;


23 import com.sun.webui.jsf.component.Head;


24   import com.sun.webui.jsf.component.Html;


25   import com.sun.webui.jsf.component.Label;


26   import com.sun.webui.jsf.component.Link;


27   import com.sun.webui.jsf.component.Message;


28   import com.sun.webui.jsf.component.Page;


29   import com.sun.webui.jsf.component.StaticText;


30   import com.sun.webui.jsf.component.TextField;


31   import javax.faces.FacesException;


32   import javax.faces.application.FacesMessage;


33   import javax.faces.component.UIComponent;


34   import javax.faces.component.html.HtmlPanelGrid;


35   import javax.faces.context.FacesContext;


36   import javax.faces.validator.LengthValidator;


37   import javax.faces.validator.ValidatorException;


31   public class Validation extends AbstractPageBean

32   {


33        private int __placeholder;


1            private void _init() throws Exception

2            {


3                   nameLengthValidator.setMaximum( 30 );


4            } // end method _init


12        // To save space, we omitted the code in lines 34-407. The complete


13        // source code is provided with this chapter's examples.


1             // validates entered email address against the regular expression


2             // that represents the form of a valid email address.


3             public void emailTextField_validate( FacesContext context,


4                    UIComponent component, Object value )

5             {


6                    String email = String.valueOf( value );


1                    // if entered email address is not in a valid format


2                    if ( !email.matches(


3                          "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*" ) )

4                    {


5                          throw new ValidatorException( new FacesMessage(


6                                 "Enter a valid email address, e.g. user@domain.com" ) );

7                    } // end if


8             } // end method emailTextField_validate


424      // validates entered phone number against the regular expression


425      // that represents the form of a valid phone number.


426      public void phoneTextField_validate( FacesContext context,


427             UIComponent component, Object value )

428      {


429             String phone = String.valueOf( value );


431             // if entered phone number is not in a valid format


432             if ( !phone.matches(


433                   "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}" ) )

434             {


435                   throw new ValidatorException( new FacesMessage(


436                         "Enter a valid phone number, e.g. (555) 555-1234" ) );

437             } // end if


438      } // end method phoneTextField_validate


440      // displays the values the user entered


441      public String submitButton_action()

442      {


443             String name = String.valueOf( nameTextField.getValue() );


444             String email = String.valueOf( emailTextField.getValue() );


445             String phone = String.valueOf( phoneTextField.getValue() );


446             nameResult.setValue( name );


447             emailResult.setValue( email );


448             phoneResult.setValue( phone );


449             resultGridPanel.setRendered( true );


450             resultText.setRendered( true );


451             return null;


452      } // end method submitButton_action


453    } // end class Validation


Fig. 26.16 | Page bean for validating user input and redisplaying that input if valid.

For the emailTextField_validate method, we use the validation expression




Note that each backslash in the regular expression String (line 417) must be escaped with another backslash (as in \\), because the backslash character normally represents the beginning of an escape sequence in Java. This regular expression indicates that an e-mail address is valid if the part before the @ symbol contains one or more word characters (i.e., alphanumeric characters or underscores), followed by zero or more Strings comprised of a hyphen, plus sign, period or apostrophe and additional word characters. After the @ sym-bol, a valid e-mail address must contain one or more groups of word characters potentially separated by hyphens or periods, followed by a required period and another group of one or more word characters potentially separated by hyphens or periods. For example, the e-mail addresses bob's-personal.email@white.email.com, bob-white@my-email.com and bob.white@email.com are all valid. If the user enters text in emailTextField that does not


have the correct format and attempts to submit the form, lines 419–420 throw a Valida-torException. The Message component catches this exception and displays the message in red.


The regular expression in phoneTextField_validate ensures that the phoneTextBox contains a valid phone number before the form is submitted. The user input is matched against the regular expression


((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}


(Again, each backslash is escaped in the regular expression String in line 433.) This ex-pression indicates that a phone number can contain a three-digit area code either in pa-rentheses and followed by an optional space or without parentheses and followed by a required hyphen. After an optional area code, a phone number must contain three digits, a hyphen and another four digits. For example, (555) 123-4567, 555-123-4567 and 123-4567 are all valid phone numbers. If a user enters an invalid phone number, lines 435–436 throw a ValidatorException The Message component catches this exception and dis-plays the error message in red.


If all six validators are successful (i.e., each TextField contains data, the name is less than 30 characters and the e-mail address and phone number are valid), clicking the Submit button sends the form’s data to the server. As shown in Fig. 26.15(d), the submitButton_action method displays the submitted data in a gridPanel (lines 446– 449) and a success message in resultsText (line 450).

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.