Reputation: 139
I've used validators with backing objects and annotations in Spring MVC (@Validate). It worked well.
Now I'm trying to understand exactly how it works with the Spring manual by implementing my own Validate. I am not sure as to how to "use" my validator.
My Validator:
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.myartifact.geometry.Shape;
public class ShapeValidator implements Validator {
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz) {
return Shape.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "x", "x.empty");
ValidationUtils.rejectIfEmpty(errors, "y", "y.empty");
Shape shape = (Shape) target;
if (shape.getX() < 0) {
errors.rejectValue("x", "negativevalue");
} else if (shape.getY() < 0) {
errors.rejectValue("y", "negativevalue");
}
}
}
The Shape class that I seek to validate:
public class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public Shape() {}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
Main method:
public class ShapeTest {
public static void main(String[] args) {
ShapeValidator sv = new ShapeValidator();
Shape shape = new Shape();
//How do I create an errors object?
sv.validate(shape, errors);
}
}
Since Errors is just an interface, I can't really instantiate it like an ordinary class. How do I actually "use" my validator to confirm that my shape is either valid or invalid?
On a side note, this shape should be invalid since it lacks an x and a y.
Upvotes: 9
Views: 5844
Reputation: 1831
Why don't you use the implementation that spring offers org.springframework.validation.MapBindingResult
?
You can do:
Map<String, String> map = new HashMap<String, String>();
MapBindingResult errors = new MapBindingResult(map, Shape.class.getName());
ShapeValidator sv = new ShapeValidator();
Shape shape = new Shape();
sv.validate(shape, errors);
System.out.println(errors);
This will print out all that is in the error messages.
Good luck
Upvotes: 20