我想使用注释针对一组值验证字符串.
I want to validate a string against a set of values using annotations.
我想要的基本上是这样的:
What I want is basically this:
@ValidateString(enumClass=com.co.enum)
String dataType;
int maxValue;
int minValue;
int precision;
或
@ValidateString(values={"String","Boolean", "Integer"})
String dataType;
int maxValue;
int minValue;
int precision;
我还想根据 dataType
中设置的值对其他变量进行一些验证:
I also want to do some validation on other variables depending upon the value set in dataType
:
if (dataType = "String") {
// maxValue, minValue, precision all should be null or zero
}
我想不出通过自定义注释来实现这一点的方法.
有人请帮帮我.
I can't think of a way to achieve this by custom annotations.
Somebody please help me.
这就是我所做的.
注释
public @interface ValidateString {
String[] acceptedValues();
String message() default "{uk.dds.ideskos.validator.ValidateString.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
验证类
public class StringValidator implements ConstraintValidator<ValidateString, String>{
private List<String> valueList;
@Override
public void initialize(ValidateString constraintAnnotation) {
valueList = new ArrayList<String>();
for(String val : constraintAnnotation.acceptedValues()) {
valueList.add(val.toUpperCase());
}
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return valueList.contains(value.toUpperCase());
}
}
我用它喜欢
@ValidateString(acceptedValues={"Integer", "String"}, message="Invalid dataType")
String dataType;
Long maxValue;
Long minValue;
现在我需要弄清楚如何实现条件检查IE.如果是字符串,那么 maxValue 和 minValue 应该为 null 或零..
Now I need to figure out how to implement conditional check ie. if String then maxValue and minValue should be null or Zero..
有什么想法吗?
这篇关于使用枚举值和注解的 Java 字符串验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!