0
 @RequestMapping("/validateMsg")
     public boolean validateEmp(@ModelAttribute Employee emp,BindingResult bindingResult,Model model){
         boolean iserror=false;
                 if(emp.getFirstName()=="")
                 {
                     model.addAttribute("firstName","firstName is required");
                     iserror=true;
                 }
         return iserror;
}

I have written this code is this correct

1 Answer 1

1

You can use a validator.

@Component
public class EmploeeValidator implements Validator{
    @Override
    public boolean supports(Class<?> clazz) {
        return Emploee.class.equals(clazz);
    }
    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "someProp", "someProp.empty");
        //other valdiation...
    }
}

Then in the controller

    @Autowired
    private EmploeeValidator validator;
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

Use it:

 @RequestMapping("/emploee")
 public boolean addEmp(@Valid Employee emp,Errors errors){
         if(errors.hasErrors()){
            //it's not valid
         } else {
            //ok
         }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.