Custom Validations :(Prepared by Appaji,senior software engineer) Requirements: Custom validations are required if default validations are not sufficient to fulfill the needs.
Struts 2 allows the use of Custom validators through the @CustomValidator annotation
Framework used:struts2
Approach:
1. In existing struts project add the fallowing code in jsp
<s:actionerror/>
<s:fielderror/>
<s:textfield
name="price"
size="20"
label="price"/>
2. Add CustomValidator to setPrice() method.
The @CustomValidator annotation takes two parameters, type and message
<?xml
version="1.0"
encoding="UTF-8"?>
<!DOCTYPE
validators
PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator
name="pricefield"
class="com.gdas.gdas.web.action.PriceValidator"/>
</validators>
note:dont include existing validators inside validators.xml
4. Create PriceValidator by extending the FieldValidatorSupport class
import
org.apache.struts.action.ActionErrors;
import
org.apache.struts.action.ActionMessages;
import
org.apache.struts2.components.ActionError;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.Validator;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport; public
class PriceValidator extends FieldValidatorSupport {
@Override
public
void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
Object value = this.getFieldValue(fieldName, object);
System.out.println("fieldName-->"+fieldName+"value-->"+value);
if(value==null) {
setDefaultMessage("You enter null");
addFieldError(getDefaultMessage(), object);
return ;
}
if((Integer)value==111) {
setDefaultMessage("You enter 111");
addFieldError(getDefaultMessage(), object);
return ;
}
try {
Integer price=(Integer)value;
return;
}catch(Exception e) {
addFieldError(fieldName, object);
}
}
}
The addFieldError method is used add any failed validations to the list of errors to be displayed.
The getFieldName and getFieldValue methods are implemented in the superclasses to retrieve the field name and field value for the field beign validated.
The custom validator may extend the FieldValidatorSupport or the ValidatorSupport classes.
Let me know if you have any queries on this,
Regards ,
Appaji,
can we rename the validators.xml file and configure in struts
ReplyDeletehulpfull post
ReplyDeletethanks you very mutch