Tuesday 18 December 2012

Regular Expression validation in ADF


We can use regular expressions for validations in ADF.
  • For UI input components we can use regex as below:
<af:inputText label="Label 1" autoSubmit="true">
 <af:validateRegExp pattern="[0-9]{1,10}"
                               noMatchMessageDetail="Only Numbers are allowed"/>
</af:inputText>
<af:commandButton text="commandButton 1"/>

In above example, the moment we tab out of input text, we get an error message with the text we provided.

  • We can also write our custom validator in managed bean:
    public void inputTextValidator(FacesContext facesContext,
                                   UIComponent uIComponent, Object object) {
        // Add event code here...
    }


 <af:inputText label="Label 1" id="it3"
                            validator="#{pageFlowScope.UIBean.inputTextValidator}">              
              </af:inputText>


  • Also we can use regex in the model layer with an attribute level validator - this will eliminate getting wrong data if someone uses the same business service in another UI.

Some common regex examples are:

Validation for decimal places

 String REGEX_CHECK_DECIMAL =
            "^-?\\d{1," + (length - decimal) + "}(?>\\.\\d{1," + decimal+ "})?$";

where length is total length of the String and decimal is no of decimal digits.

Validation for String uppercase

String REGEX_CHECK_UPPERCASE ="[A-Z]+";

more to come....

3 comments:

  1. Hi Bharat, could you please help create in reqular expression for following condition.

    1. Should take only number
    2. Should enter number between 00.00 to 24.00
    3. 2 digits decimal only

    ReplyDelete
    Replies
    1. Hi Rick,

      Use below pattern:

      String regex="([01][0-9]|2[0-4])\\.[0-9][0-9]";

      Delete
  2. Hi Bharat,

    Please help..!!

    could you please tell the Regular Expression for following pattern for input box:

    nn(nn)-nnnn-nn

    Condition is :

    There should be 2 to 4 characters followed by a dash (-), then four characters followed by another dash and finally two more characters.

    Valid Formats:

    nn-nnnn-nn

    nnn-nnnn-nn

    nnnn-nnnn-nn

    n is a character

    Condition for Fail :

    1) Validation fails if user enters more than 12 chars.
    2) No need to do any validation if user enters less than 10 chars.
    3) Do validation for "nn(nn)-nnnn-nn" pattern only if user enters 10, 11 or 12 characters.

    -Regards,
    Samrendra

    ReplyDelete