1

I have a register form. When I post the form, this error Failed to convert property value of type [java.lang.String] to required type [int] for property number; nested exception is java.lang.NumberFormatException: For input string: "wewer" come. So I am looking for a simple way to check the type of the data. I have tried to use @Pattern(regexp = "[A-Za-z]", message = "digits only") but this won't work. Is there any one line annotation to use?

Updated: Thanks RC for the idea. create a string for number, then convert it back later. I think my solution is not good, because I have to add one entry in the User class, change the field in the register form.

@Component
public class UserValidator implements Validator {

    @Override
    public boolean supports(Class clazz) {
      return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
      User user = (User) target;

      if(user.getUsername() == null || user.getUsername() == "") {
          errors.rejectValue("username", "","username is empty");
      }
    if(user.getNumberString().isDigit == false) {
        errors.rejectValue("number", "","digits only");
    } else {
        user.setNumber(Integer.parseInt(user.getNumberString());
    }

}

And my User class.

public class User {
    private int id;

    private String username;

    //@Pattern(regexp="[A-Za-z]" ,message = "No characters")
    //@NotNull
    @Min(3)
    private Integer number;
    private String numberString;

}
peter
  • 69
  • 1
  • 10
  • == with strings??? –  Dec 02 '16 at 06:00
  • @RC Sorry I forgot to update my User class, the number is an Integer – peter Dec 02 '16 at 06:15
  • `user.getUsername() == ""` is incorrect. Use `equals()` to compare strings instead of `==`. See: [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839) – Jesper Dec 02 '16 at 09:15
  • Use a string for "number" with `@Pattern` or `@Digits` and convert it back to some int when you use it? –  Dec 02 '16 at 09:15
  • @RC thanks for your idea, I have made some update. – peter Dec 02 '16 at 09:58

0 Answers0