티스토리 뷰

Creating Custom JSF Validation

You can add your own validation logic to meet your specific business nedds. If you need custom validation logic for a component on a single page, you can create a validation method on the page's backing bean. Creating the validation method on a backing bean is also useful when you need validation to access other fields on the page. For example, if you have separate date fields (month, day, year) and each has its own validator, users will not get an error if they enter February 30, 2005. Instead, a backing bean for the page can contain a validataion method that validates the entire date.

If you need to create logic  that will be reused by various pages within the application, or if you want the validation to be able to run on the client side, you should create a JSF validator class.

How to create a backing bean validation method

To add a backing bean validation method:
  1. Insert the component that will require validation into the JSF page.
  2. Add the needed validation logic to backing bean. This logic should use javax.faces.validator.ValidatorException to throw the appropriate exceptions and javax.faces.application.FacesMessage to generate the corresponding error messages. For more information about the Validator interface and FacesMessage, see the Javadoc fo javax.faces.validator.Validator and javax.faces.application.FacesMessage, or visit http://java.sun.com/.
What happens when you create a backing bean validation method

Managed bean code for a validation method

public void inputValidator (FacesContext facesContext, UIComponent uiComponent, Object object) {
    // Add event code here...
}

Sample code for validation method

public void defaultValidator(FacesContext context, UIComponent component, Object value) {
    System.out.println("value::"+value);
    if (value != null) {
        if (value.equals("admin1")) {
            System.out.println("It matches with 'admin1'");
            return;
        }
    }
    ((UIInput)value).setValid(false);
    FacesMessage msg = new FacesMessage("I am a real exception.");
    context.addMessage(component.getClientId(context), msg);
}

JSF code for a custom validation method

<h:inputText accesskey = "true" id="Login_Name" value="#{LoginBean.loginName}" styleClass="login_input" validator="#{LoginBean.defaultValidator}" required="true">
    <f:validateLength maximum="35"/>
</h:inputText>
<h:commandButton value="Submit" style="margin-left: 15px; margin-top: 8px;" action="#{LoginBean.submit}" image="../images/btn_continue.jpg">

How to create a custom JSF validator

Create a custom validator requires writing the business logic for the validation by creating a Validator implemntation that contains a method overriding the validate method of the Validator interface, and then registering the custom validator with the application. You can also create a tag for the validator, or you can use the validator tag and nest  the custom validator as a property of that tag.

You can then create a client-side version of the validator.

To create a custom JSF validator
  1. Create a Java class that implements the javax.faces.validator.Vliadator interface. The implementation must contain a public no-args constructor, a set of accessor methods for any attributes, and a validate method that overrides the validate method of the Validator interface.
    Alternatively, you can implement the javax.faces.FormatValidator interface, which has accessor methods for setting the formatPatterns attribute. This attribute specifies the acceptable patterns for the date entered into the input component. For example, if you wnat to validate the pattern of a credit card number, you create a formatPatterns attribute for the allowed patterns. The implementation must contain a constructor, a set of accessor methods for any attributes, and a validate method that overrides the validate method on the Validator interface.

    For both interfaces, the validator method takes the FacesContext instance, the UI compoent, and the data to be validated. For example:

    public void validate(FacesContext facesContext, UIComponent uiComponent, Object object) {
       ...
    }
    For more information about these classes, refer to the Javadoc or visit http://java.sun.com/.
  2. Add the needed validation logic. This logic should use javax.faces.validator.ValidatorException to throw the appropriate exceptions and javax.faces.application.FacesMessage to generate the corresponding error message. For more information about the Validator interface and FacesMessage, see the Javadoc for javax.faces.validator.Validator and javax.faces.application.FacesMessage, or visit http://java.sun.com/.
  3. If your application saves state on the client, make your custom validator implementation implement the Serializable interface, or implement the StateHolder interface, and the saveState(FacesContext) and restoreState(FacesContext, Object) methods for StateHolder. For more information, see the Javadoc for the StateHolder interface of the javax.faces.component package.
  4. Register the validator in the faces-config.xml file.
    • Open the faces-config.xml file in the editor. The faces-config.xml file is located in the /WEB-INF directory.
    • Make the validator available
    • <validator>
          <validator-id>VALIDATOR_NAME</validator-id>
          <validator-class>VALIDATOR_CLASS</validator-class>
      </validator>
  5. Optionally create a tag for the validator that sets the attributes for the class. You create a tag by adding an entry for the tag in the application's tag library definition file (TLD). To do so:
    • Open or create a TLD for the application. For more information about creating a TLD, visit http://java.sun.com/.
    • Define the validator ID and class as registered in the faces-config.xml file.
To create a client-side version of the validator:
  1. Write a JavaScript version of the validator, passing relevant information to a constructor.
  2. Extends the javax.faces.webapp.ValidatorTag and override createValidator method.
To use a custom validator on a JSF page:
  • To use a custom validator that has a tag on a JSF page, you need to manually nest it inside the component's tag. shows a custom validator nested inside an inputText component. Note that the tag attributes are used to provide the values for the validator's properties that were declared in the faces-config.xml file.
    <h:inputText id="empnumber" required="true">
    // todo: needed modify
    </h:inputText>
To use a custom validator without a custom tag:

To use a custom validator without a custom tag, you must nest the validator's ID (as Configured in faces-config.xml file) inside the validator tag.
// todo: needed modify

What happens when you use a custom JSF validator

When you use a custom JSF validator, the application accesses the validator class referenced in either the custom tag or the validator tag and executes the validate method. THis method accesses the data from the component in the current FacesContext and executes logic against it to determine if it is valid. If the validator has attributes, thos attributes are also accessed and used in the validation routine. Like standard vaildators, if the custom validation fails, associated messages are placed in the message queue in FacesContext.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/11   »
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
글 보관함