Saturday, July 18, 2009

JSF Validator

You can use Custom Validator for validating editable component in JavaServer Faces. Java Community provide an Interface called "Validator" it hava method validate() having
syntax:
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException

You need to implement this interface and provide the implementation for validate method.
Example:-

package com.validators;
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 NameValidator implements Validator
{
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException
{
String name = (String) value;
String errorLabel = "Please enter a valid Name.";
if(!component.getAttributes().isEmpty())
{
errorLabel = (String) component.getAttributes().get("errordisplayval");
}
if(name.length()==0)
{
;
}
else
{
String namePattern = "[a-zA-Z_]+";
boolean retval = name.matches(namePattern);
if(!retval name.length()>8)
{
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(errorLabel);
message.setDetail(errorLabel);
throw new ValidatorException(message);
}
}
}
}

No comments:

Post a Comment