Is it possible to return multiple / variable error messages with a single (preferably Spring-based) custom annotation?
I'm currently using Spring for all of my validation, but wanted to build a custom annotation to group together a number of conditions on a single field, validating some of them conditionally and with variable values, ie something along the lines of:
public @interface CustomAnno
{
@NotNull
@Length(min = 1, max = 10, applyIf = "condition == 1")
@Length(min = 11, max = 20, applyIf = "condition == 2")
String val();
int condition();
}
I know that isn't syntactically correct, but hopefully that gets the point across of what I'm trying to do.
My question is, is something like the above even possible, and would that single CustomAnno annotation be able to return errors for all of the conditions that fail, instead of just returning a single failure for CustomAnno?
Edit: I may not necessarily be using Spring annotations to drive the validation for a value. Ideally I would be using arbitrary validation logic in the ConstraintValidator that handles CustomAnno, 开发者_Go百科which if my understanding is correct will only return true or false for one possible error in the isValid call. What I'm actually looking for is something that achieves the same functionality as the above, but with either annotations or custom logic from the validator, ie:
public class CustomAnnoValidator implements ConstraintValidator<CustomAnno,String>
{
@NotNull
String val;
int cond;
String regex;
List<String> errors;
private void err(String msg)
{
errors.add(msg);
}
public void initialize(CustomAnno anno)
{
this.val = anno.val();
this.cond = anno.condition();
this.errors = new ArrayList<String>();
this.regex = "[A-Za-z]+[A-Za-z0-9]+";
}
public boolean isValid(String object, ConstraintValidatorContext constraintContext)
{
if (cond == 1)
{
if (object.length() > 10)
err("Length must be less than 10");
else if (object.length() < 1)
err("Length must be greater than 1");
}
else if (cond == 2)
{
if (object.length() > 21)
err("Length must be less than 21");
else if (object.length() < 10)
err("Length must be greater than 10");
}
if (!val.matches(regex))
err("Must start with an alpha character and consist of only alphanumeric characters.");
// some method to add the error messages, ie => constraintContext.addErrors(errors);
return errors.size() > 0;
}
}
I guess theoretically I could create custom annotations for any of the single conditions that I am missing, potentially making this question a wash, but was wondering if it were possible for the validator to handle multiple conditions
I'm not sure what you mean by Spring annotations? Spring MVC is designed to work with JSR-303, which is what those javax.validation jars describe.
Spring MVC validation should return error messages for every failed validation, even if those validations are grouped together in a single custom annotation.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html
精彩评论