1

I have textfield array which has to accept only numeric values i.e. 1-5.

<s:textfield name="marks[0]" maxlength="1" /> 
<s:textfield name="marks[1]" maxlength="1" /> 
<s:textfield name="marks[2]" maxlength="1" />  and so on upto 9 textfields.

I have getter/setter methods for this as follows

public List<Integer> getMarks(){
     return marks;
}
public void setMarks(List<Integer> marks){
     this.marks = marks;
}

How to ensure that user does not enter non numeric values like alphabets? If I enter character it throws runtime exception 'java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer ' pointing to validate method in the Next JSp page.

public void validate(){
  for(i=0;i<9;i++){
     if (marks.get(i)>5)     //this line throws above ClassCastException
    addFieldError("...");
  }
}

How to solve this exception as well as validation to continue? In other Pages where single textfield is there, invalid.fieldvalue.error is displayed but for List I am getting above exception

sowmya r a
  • 67
  • 1
  • 1
  • 5

2 Answers2

1

Just put your validation logic inside try catch block

public void validate(){
  try{
    for(i=0;i<9;i++){
      if (marks.get(i)>5)     //this line throws above ClassCastException
        addFieldError("...");
    }
  }catch(Exception e){
  }
}
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
  • Now it is working,but I am getting 2 field errors now. One is invalid field error from the ConversionErrorInterceptor where fieldName is displayed as marks[0] or marks[1] and other one which i added in catch block using addFieldError which is clear to understand.How to display only custom message – sowmya r a Dec 19 '12 at 05:38
  • Do not add your custom message and see this link http://struts.apache.org/2.x/docs/type-conversion.html#TypeConversion-TypeConversionErrorHandling. – Aleksandr M Dec 19 '12 at 09:56
0

I usually do it that way (may be there is better solution)

public void setMarks(List<String> marksStr){
  List<Integer> marks = new ArrayList();

  for(String markStr : marksStr) {
    try {
      Integer mark = Integer.parseInt(markStr);
      marks.add(mark);
    } catch (NumberFormatException e) {
      addFieldError("", "Wrong mark value: " + markStr);
    }
  }
  this.marks = marks;
}
Vasily Komarov
  • 1,405
  • 9
  • 11
  • Do NOT put validation logic inside setters/getters. – Aleksandr M Dec 18 '12 at 21:08
  • @Vaisly Komarov-I tried this as well but still it is throwing exception.I go with Aleksandr M that should not put validation logic inside setters/getters. Thank you for your answer, may be in some other code it may be useful for me. – sowmya r a Dec 19 '12 at 05:47