Thursday, August 4, 2011

CUSTOM VALIDATOR


In my last post I included information about different validations available in ADF-BC. These validations are very easy to apply in Entity object and view objects. There are most of the possible validations are available. Still you may want to define your own custom validation, for this you will write code in your managed bean. 
To apply a custom validator go to your jspx or jsff page and select the input text or other input component an go to its properties. Give a function name to validator.

 
This validator will look like :
public void NameValidation(FacesContext facesContext, UIComponent uIComponent, Object object) {

return true:

}


Now in this validator method you can write your own validation code. Such as I have written here validation of name input text, so that user can only insert capital letters, numbers and “_”. If validation fails it will show a error, else nothing.
public void NameValidation(FacesContext facesContext, UIComponent uIComponent, Object object) {
        String value = (String)object;
        if ((value == null) || value.length() == 0) {
            return;
        }
        String expression = "^[A-Z 0-9_]{2,100}$";
        CharSequence inputStr = value;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        String error = “Only upper case letter and _ allowd”;
        if (matcher.matches()) {
        } 
else {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error, null));
        }
    }

When you run application and validation fails you will get an error like this:

2 comments:

  1. Thank you for your post. It was useful.

    But I have another question:

    what about if the validation of the field depends on another field value?

    In my project I need to check if another field (a select one choice) has been selected. If yes, the field which I'm validating is required.

    My problem is "how I retrieve the value of the other field from the validate method of the interested field".

    Can you help me someway?

    Thank you.

    Riccardo

    ReplyDelete
    Replies
    1. Hello Riccardo,

      You want to make a field required on the basis of a select choice field.

      If this what you want then make a function on bean class which return Boolean value. In this method get value from select choice field using this field's view object, as direct getting value from choice list will give index not value. View object' attribute will give you the value.
      After getting value check value for your condition in if statement and return true in method.

      Main part is go to page select field which you want to make required, go to its required property and select previously created method, so that whenever this function will return true your field will become required.

      Regards
      Rohit

      Delete