Custom JSF Validator

How to Create your custom validator?
suppose that we want to create custome validator that applies some Arithmatic Operation on two fields.

1. Create the ComparisonValidator.2- Create the ComparisonValidatorTag. 3- Create the Validator.tld 4- Register the validator in the faces-config.xml 5- Now in the jsp page you can use it as following:


1. Create the ComparisonValidator.

package com.aliabdelaziz;

/**
*
* @author aabdelaziz
*/
public class ComparisonValidator extends ValidatorBase
{
static Logger _logger = Logger.getLogger(ComparisonValidator.class);
/**
* Creates a new instance of FromThruValidator
*/
public ComparisonValidator() {
}
/**
*

The standard converter id for this converter.

*/
public static final String VALIDATOR_ID =
"com.aliabdelaziz.ComparisonValidator";

/**
*

The message identifier of the {@link FacesMessage} to be created if
* the equal_for check fails.

*/
public static final String EQUAL_MESSAGE_ID = "ArithmeticValidator";

//the foreign component_id on which the validation is based.
private String _for= null;
private String _operation= null;

// -------------------------------------------------------- ValidatorIF
public void validate(FacesContext facesContext, UIComponent uiComponent,
Object value) throws ValidatorException
{
_logger.info(" Now validating... validate(FacesContext facesContext,
UIComponent uiComponent, Object value) ");

if (facesContext == null) throw new NullPointerException("facesContext");
if (uiComponent == null) throw new NullPointerException("uiComponent");
if (value == null)
{
return;
}

UIComponent foreignComp = uiComponent.getParent().findComponent(_for);
if(foreignComp==null)
throw new FacesException("Unable to find component '" + _for + "' (calling
findComponent on component '" + uiComponent.getId() + "')");

if(false == foreignComp instanceof EditableValueHolder)
throw new FacesException("Component '" + foreignComp.getId() + "' does not
implement EditableValueHolder");

EditableValueHolder foreignEditableValueHolder =
(EditableValueHolder) foreignComp;

if (foreignEditableValueHolder.isRequired() &&
foreignEditableValueHolder.getValue()== null )
{
return;
}

Object[] args = {value.toString(),(foreignEditableValueHolder.getValue()==null) ? foreignComp.getId():foreignEditableValueHolder.getValue().toString()};

if(_operation.equals("greaterThan"))
{
//do the comparison for greaterThan here
}
else if(_operation.equals("lessThan"))
{
//do the comparison for lessThan here
}
else if(_operation.equals("equal"))
{
//do the comparison for equal here
}
else
{
// means this is un known charactar.
FacesMessage message = new FacesMessage();
_logger.info("******> Message = " +
Messages.getMessageString("ComparisonValidator"));

message.setDetail(Messages.getMessageString("ComparisonValidator"));

message.setSummary(Messages.getMessageString("ComparisonValidator"));
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
// -------------------------------------------------------- StateholderIF

public Object saveState(FacesContext context)
{
Object values[] = new Object[6];
values[0] = super.saveState(context);
values[1] = _for;
values[1] = _operation;
return values;
}

public void restoreState(FacesContext context, Object state)
{
Object values[] = (Object[])state;
super.restoreState(context, values[0]);
_for = (String)values[1];
_operation = (String)values[2];
}
// -------------------------------------------------------- GETTER & SETTER

/**
* @return the foreign component_id, on which a value should be validated
*/
public String getFor()
{
return _for;
}

/**
* @param string the foreign component_id, on which a value should be validated
*/
public void setFor(String string) {
_for = string;
}

/**
* @return the Comparison operation name.
*/
public String getOperation()
{
return _operation;
}

/**
* @param string the Comparison operation
*/
public void setFor(String string) {
_operation = string;
}
}


2- Create the ComparisonValidatorTag.

/**
*
* @author aabdelaziz
*/
public class ComparisonValidatorTag extends ValidatorBaseTag {

/**
* Creates a new instance of ComparisonValidatorTag
*/
public ComparisonValidatorTag() {
}

private static final long serialVersionUID = -3249115551944863108L;
//the foreign component_id on which the validation is based.
private String _for = null;

public void setFor(String string) {
_for = string;
}

private String _operation = null;

public void setOperation(String string) {
_operation = string;
}

protected Validator createValidator() throws JspException
{
FacesContext facesContext = FacesContext.getCurrentInstance();
setValidatorId(ComparisonValidator.VALIDATOR_ID);
ComparisonValidator validator = (ComparisonValidator)super.createValidator();
if (_for != null)
{
if (UIComponentTag.isValueReference(_for))
{
ValueBinding vb = facesContext.getApplication().createValueBinding(_for);
validator.setFor(new String(vb.getValue(facesContext).toString()));
}
else
{
validator.setFor(_for);
}
}

if (_operation != null)
{
if (UIComponentTag.isValueReference(_operation)))
{
ValueBinding vb = facesContext.getApplication().createValueBinding(_operation);
validator.setMethodName(new String(vb.getValue(facesContext).toString()));
}
else
{
validator.setMethodName(_operation);
}
}

return validator;
}

public void release() {
super.release();
_for = null;
_operation = null;
}
}


3- Create the Validator.tld

<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>cv</short-name>
<uri>/WEB-INF/validators</uri>
<description>
MyFaces subproject that contains components and other goodies to be used with any JSF implementation.
</description>

<tag>
<name>validateComparison</name>
<tag-class>com.aliabdelaziz.ComparisonValidatorTag</tag-class>
<body-content>JSP</body-content>
<description>
A custom validator for validations against foreign component values.

Unless otherwise specified, all attributes accept static values or EL expressions.
</description>
<!--
This attribute indicates an alternate validation error message format string to display.
-->
<attribute>
<name>message</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description>
alternate validation error message format string
</description>
</attribute>

<name>for</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
<description>
the id of the foreign component, which is needed for the validation
</description>
</attribute>
<attribute>
<name>operation</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
<description>
the id of the foreign component, which is needed for the validation
</description>
</attribute>
</tag>
</taglib>


4- Register the validator in the faces-config.xml

<validator>
<validator-id>com.oc.itworx.HR.validators.employmentFromDateValidator</validator-id>
<validator-class>com.oc.itworx.HR.validators.EmploymentFromDateValidator
</validator>


5- now in the jsp page you can use it as following:

<%@ taglib uri="/WEB-INF/validators" prefix="cv"%>

<h:inputText maxlength="7" id="Input_1" value="#{managedBean.input1}" required="true" />

<h:inputText maxlength="7" id="Input_2" value="#{managedBean.input2}" required="true" >

<cv:validateRangesOverlapping for="Input_1" methodName="lessThan"/>

</h:inputText>


uhinut

tuyệt vời Văn bản mà Tôi có đã được hiểu Tôi thích các item nhưng nó sẽ được nhiều hấp dẫn khi bạn sản xuất Văn bản liên quan đến kỳ nghỉ người giống như tại đây blog . Travel Pulau Tidung

The program is not that easy

The program is not that easy to know. Most especially when we talked about documentation. - Flemings Ultimate Garage

Powered by Drupal - Design by artinet