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;
}