When I enter in the field "Age" (which is an Integer), any data other than numbers, an error occurs. I need just to show error message from my validator.
my model:
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private Boolean isAdmin;
@GeneratedValue
private Timestamp createdDate;
Validator:
public class FormValidator implements Validator {
private Pattern pattern;
private Matcher matcher;
@Override
public boolean supports(Class<?> aClass) {
return true;
}
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name", "Mess1", "Mess2");
if(!(user.getName()!= null && user.getName().isEmpty())) {
pattern = Pattern.compile("[a-zA-Z]+");
matcher = pattern.matcher(user.getName());
if (!matcher.matches()) {
errors.rejectValue("name", "name contains non char", "enter a valid name");
}
if (user.getAge() != null) {
pattern = Pattern.compile("[0-9]{0,3}");
matcher = pattern.matcher(user.getAge().toString());
if (!matcher.matches()) {
errors.rejectValue("age", "mess1", "mess2");
}
if (user.getAge().toString().length() > 3) {
errors.rejectValue("age", "age to big", "not more 3 int");
}
}
}
}
}
Controller:
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingUser(@ModelAttribute User user, BindingResult result) {
FormValidator formValidator = new FormValidator();
formValidator.validate(user,result);
if(result.hasErrors()){
ModelAndView modelAndView = new ModelAndView("add-user-form",result.getModel());
return modelAndView;
}
ModelAndView modelAndView = new ModelAndView("home");
userService.addUser(user);
String message = "User was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
I understand that the error arises from the fact that the page receives the old wrong object from the completed form, with field "age" (in which, data other than numbers).
But if I send a new object and BindingResult to form separately , the errors is not shows. Like this:
if(result.hasErrors()){
ModelAndView modelAndView = new ModelAndView("add-user-form");
modelAndView.addObject("user,new User()");
modelAndView.addObject("errors",result);
return modelAndView;
}
How can i send BindingResult separately from bad object or how can I avoid this?
error image: https://i.stack.imgur.com/YVlt6.png