Struts2 Validation for an array

后端 未结 1 605
别跟我提以往
别跟我提以往 2020-12-22 03:24

Question: how to validate the elements of an array?

I want to write a simple application that asks a user to enter 10 numbers using struts2.

enter.js

相关标签:
1条回答
  • 2020-12-22 04:30

    It is unlikely you are going to reuse this validator, so just use validate within the action:

    import com.opensymphony.xwork2.ActionSupport;
    import java.util.ArrayList;
    
    public class NextAction extends ActionSupport{
        private Integer[] number;
    
        public Integer[] getNumber() {
            return number;
        }
        public void setNumber(Integer[] number) {
            this.number = number;
        }
        //Following is default behaviour so it is not worth writing
        //public String execute(){
        //    return "success";
        //}
    
        //add validation in action (_not tested_)
        public void validate(){
            if (number.length > 10){
              this.addActionError("Error: More than ten numbers supplied.");
            }else if (number.length < 10){
              this.addActionError("Error: Less than ten numbers supplied.");
            }
            for (int i = 0; i < number.length; i++){
               if(number[i] < 0){
                 this.addActionError("Error: Number " + (i + 1) + " is less than zero.");
               }else if(number[i] > 100){
                 this.addActionError("Error: Number " + (i + 1) + " is greater than 100.");
               }
            }
        }
    }
    

    Then display the field errors in the jsp with <s:actionerror /> or rewrite the above to specifically name fields (with indexes) in which case you can use , and you'll use the addFieldError method. For details on these tags see http://struts.apache.org/2.3.1.2/docs/tag-reference.html

    0 讨论(0)
提交回复
热议问题