Flipkart Search

Wednesday 14 August 2013

ADF Custom validators for input text

ADF is very rich in providing validations out of the box whether client Side or Server Side.
Its safe to provide server side validations as well so that no can escape the validations by turning off js.
Here are the some default validators provided by ADF.
1.  ByteLengthValidator
2. DateTimeRangeValidator
3. DateRestrictionValidator
4. DoubleRangeValidator
5. LengthValidator
6. LongRangeValidator
7. RegExpValidator

Let's start making some custom Validators. I am starting with an EmailValidator
Make a Validator Class.

package com.rk.validator;


import java.io.Serializable;


import java.util.regex.Matcher;

import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


public class EmailValidator implements Serializable, Validator {


    public EmailValidator() {
        super();
    }

    public void validate(FacesContext facesContext, UIComponent uiComponent,
                         Object object) {
        String value = (String)object;
        if ((value == null) || value.length() == 0) {
            System.out.println("null value found");
            return;
            //System.out.println("null value found");
        }
        //String expression="^[\\\\w\\\\-]([\\\\.\\\\w])+[\\\\w]+@([\\\\w\\\\-]+\\\\.)+[A-Z]{2,4}$";
        String expression =
            "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        CharSequence inputstr = value;
        Pattern pattern =
            Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputstr);
        if (!matcher.matches()) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                          "Enter the proper Email Id",
                                                          null));
        }

    }
}

....................................
Now go to faces-config.xml and open validators tab give a meaningfull Id like EmailValidator and classname
in this case it should be com.rk.validator.EmailValidator

and the input file just write
<af:inputText label="Enter EmailID" id="it1" autoSubmit="true">
<f:validator validatorid="EmailValidator"/>
</af:inputText>

And you are done.

No comments:

Post a Comment