Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ValidationUtils in spring

I want to use ValidationUtils as follows. But I cannot instantiate errors object since Errors is an Interface. Can you tell me how I can make this working without using a validator?

     if(visitorDetails==null)
    {
        Errors errors;
        visitorDetails=new Visitor(); 
        ValidationUtils.rejectIfEmpty(errors, "VisitorInfo", "Selected Visitor Details Not Found");
    }
like image 951
Parag Avatar asked Jan 10 '23 02:01

Parag


1 Answers

Read this : Validation...

However you must implement the Validation interface in a class, and than use it to validate your object, and to do that you autowire validator in your controller..

This is an example:

public class PersonValidator implements Validator {

    /**
    * This Validator validates *just* Person instances
    */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
      }
}

and in your controller:

....

    @Autowired
    private PersonValidator personValidator;

    @InitBinder
    protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) {
        binder.addValidators(personValidator);
    }
...
like image 59
Teo Avatar answered Jan 22 '23 01:01

Teo