0

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Simon
  • 997
  • 1
  • 15
  • 29
  • 1
    The error occurs because of failed conversion of the value abc to integer. If I understand your problem correctly, you could just override that error message to something you want (like "Value must be number") as explained here: http://stackoverflow.com/a/28382597/1291150 – Bohuslav Burghardt Aug 09 '15 at 15:56

1 Answers1

0

Try setting error to the result object if createUser() method returns false like below code.

boolean IsUserCreated = userDAO.createUser(user);
if(isUserCreated == true) {

 } else {
   result.addError(new objectError("emailAddress", "Email ID is already in use")); // here result is BindingResult, emailAddress is the name of the input field in the form.
   modelMap.put("errors", result.getAllErrors());
 }