Friday, April 11, 2008

Struts 2 Custom Validators

Struts 2 allows the use of Custom validators through the @CustomValidator annotation. The @CustomValidator annotation takes two mandatory parameters, type and message
  • type: Refers to the "name" given to the validator in the validators.xml file.
  • message: Message to be displayed when this validator fails.
A custom validator can be implemented by extending the FieldValidatorSupport, or alternatively the ValidatorSupport classes. The following sample builds on the example built in the previous post, Struts 2 Validaton: Annotations.

To run this sample, follow these steps... There's More

  1. Create a simple struts project as described in the previous example, Struts 2 Validation : Annotations
  2. Create the new validator by extending the FieldValidatorSupport class
    package validators;

    import com.opensymphony.xwork2.validator.ValidationException;
    import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

    public class NumberFieldValidator extends FieldValidatorSupport {

    public void validate(Object object) throws ValidationException {
    String fieldName = getFieldName();
    Object value = this.getFieldValue(fieldName, object);

    if (!(value instanceof String)) {
    return;
    }

    String str = ((String) value).trim();
    if (str.length() == 0) {
    return;
    }

    try {
    Double.parseDouble(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }
    try {
    Integer.parseInt(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }

    }
    }
    NumberFieldValidator.java
    • The custom validator may extend the FieldValidatorSupport or the ValidatorSupport classes.
    • The FieldValidatorSupport class extends ValidatorSupport to add field specific information to the Field.
    • The is numeric check is performed by trying to convert the input string to Integer or Double and catching any exception.
    • 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.
  3. Declare the new custom validator in the validators.xml file. The validators.xml file must be in the classpath of the application.
    <?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="numericField" class="validators.NumberFieldValidator"/>
    </validators>
    validators.xml

    Note: The name attribute of the validator must match the type attribute of the @CustomValidator Annotation used in the Action class.
  4. Add the additional check to the Action class setPrice() method.
     @RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
    @CustomValidator(type = "numericField", message = "Price must be a number")
    public void setPrice(String price) {
    this.price = price;
    }
    AddTransactionAction.java

    Note: the type attribute of the @CustomValidator Annotation must match the name of the validator as defined in the validators.xml file.

8 comments:

  1. Hi,

    Thanks for this awesome post. I have followed in detail the steps you mentioned and am getting the following error:
    Jul 10, 2008 5:47:20 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet default threw exception
    java.lang.IllegalArgumentException: There is no validator class mapped to the name numericField

    Can you tell what I might be missing?

    Thanks!

    ReplyDelete
  2. Hi Abhi..great post. I have a question. Is it possible to access the request or the session from within the custom validator? I need to validate a captcha response from there. Thank you

    ReplyDelete
  3. Hi, would u be interested for link exchange with my blog. Here is my blog http://software-wikipedia.blogspot.com/. Mail me at software.wikipedia@gmail.com

    ReplyDelete
  4. Hello! I'm having a problema, the method 'validate' in the class 'NumericValidatorField' is having the value of the field equals 'null' no matter what type is the field value filled. does Someone know why ? Thanks!!

    ReplyDelete
  5. Hi friends,
    I have posted a clarification for the Struts2 custom validators with explanation here.go through this http://ram-ch9.blogspot.com/2009/01/struts-2-custom-validations.html

    ReplyDelete
  6. Many institutions limit access to their online information. Making this information available will be an asset to all.
    Custom Paper Writing

    ReplyDelete
  7. struts is good but why you don't use maplet class from Shine Enterprise Pattern stead struts
    refer http://www.j2os.org

    ReplyDelete
  8. you have to put this in your validators.xml to run
    "

    "

    ReplyDelete

Popular Posts