Alireza Fattahi
Alireza Fattahi

Reputation: 45475

Struts 2 manually call a custom validation in an action

We have used Struts 2 validation with lots of custom validation to validate our forms.

@Validations( 
    customValidators =      
           { @CustomValidator(type = "AccountFormat", fieldName = "accountNo") }
)

Also we can can manually validate a form by overriding the validate method

public void validate() {
    //Username can't be blank
    if(username.equals("")) {
        addFieldError("username", "The Username can't be empty");
    }

Is it possible to call the custom validations in the validate().

Why we need it ?! All validation rules are packed in custom validations, which is perfect. There are some few forms which need to have their own manual validation. We end up cut and pasting some of custom validation rules in these manual validation forms too, it would be best if we could call validations here

Upvotes: 2

Views: 845

Answers (1)

Aleksandr M
Aleksandr M

Reputation: 24396

Of course you can create an instance of your custom validator, set required properties (field name, value stack, ...) and call validate method...

BUT it is not the best way to handle such cases. What you are going to do if you need to validate values outside of the action context (e.g. in some web service)?

The better solution would be to pull validation logic from custom validator to some separate class, which you can call from anywhere in your code, and write your Struts2 custom validator as a wrapper that calls that class.

Upvotes: 3

Related Questions