Custom validation components


You will need to build your own custom validation components for data types that aren't supported by the standard JSF validators: for example e-mail addresses, zip codes or complex password validators.

Using a custom validator requires defining a Class which implements the javax.faces.validator.Validator interface:

package sample;
import java.util.regex.*;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.*;

public class ValidatorBean implements Validator
{

    private static final String EMAIL_REGEXP =
            "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";


    @Override
    public void validate(FacesContext context, UIComponent c, Object val) throws ValidatorException
    {
        String email = (String) val;
        Pattern mask = null;
        mask = Pattern.compile(EMAIL_REGEXP);
        Matcher matcher = mask.matcher(email);

        if (!matcher.matches()) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Please enter a valid email");
            message.setSummary("Email not valid");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }


    }

}

Then the validator needs to be declared in faces-config.xml
 <validator>
  <validator-id>sample.ValidatorBean"</validator-id>
  <validator-class>sample.ValidatorBean</validator-class>
 </validator>

Then, in your view, you can reference the Validator using the validatorId property:
 <h:inputText id="email" value="#{sampleBean.email}">
  <f:validator validatorId="sample.ValidatorBean"/>
</h:inputText>

Note for JSF 2 users: you can skip completely the configuration in faces-config and simply add the @FacesValidator("sample.ValidatorBean") at class level

0
0
0
s2sdefault