Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual validation in Struts 2 on specific fields

For example I have an Action Class called UsersAction where I have some methods like: login, logout, register, and so on.

And I have written validate() method as follows:

@Override
public void validate() {
    if ("".equals(username)) {
        addFieldError("username", getText("username.required"));
    }
    if ("".equals(email)) {
        addFieldError("email", getText("email.required"));
    } else if (!Utils.isValidEmail(email)) {
        addFieldError("email", getText("invalid.email.address"));
    }
    if ("".equals(phone)) {
        addFieldError("phone", getText("phone.required"));
    }
    if ("".equals(password)) {
        addFieldError("password", getText("password.required"));
    }
}

The problem is that this solution works only when register action is called, anyway it wont work on login or logout cause it will check if the fields aren't null or email is correct and always will give an error. Okay, the solution for logout was to add @SkipValidation annotation above it, but I don't know how to tell to it that login have only 2 fields username and password and that it's not necessary to check email and phone too. I don't want to write an Action Class for each action in part, cause the purpose of Struts 2 is not this.

like image 348
Ferrago Avatar asked Jun 25 '13 17:06

Ferrago


2 Answers

Create validateMethodName methods, where methodName is the name of the method, e.g.,

validateLogin() { ... }

Otherwise provide some form of contextual information to your validate method.

like image 83
Dave Newton Avatar answered Sep 24 '22 19:09

Dave Newton


Using annotations, annotate your action method login with

@Action(value="login", results = {
  @Result(name="input", location = "/login.jsp")
},interceptorRefs = @InterceptorRef(value="defaultStack", params = {"validation.validateAnnotatedMethodOnly", "true"}))
@Validations(requiredFields = {
  @RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "username", message = "${getText("username.required")}"),
  @RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "password", message = "${getText("password.required")}")
})

it will only validate username and passsword fields. Similar do the other action methods.

References:

  • Convention plugin
  • Validation
  • Validatin annotation
like image 21
Roman C Avatar answered Sep 22 '22 19:09

Roman C