以下是我创建自定义注释以验证名称的代码 ValidName.java
package custom.Annotation;
import java.lang.annotation.*;
import net.sf.oval.configuration.annotation.Constraint;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.LOCAL_VARIABLE)
@Constraint(checkWith=NameValidator.class)
public @interface ValidName {
String message() default NameValidator.message;
}
这是我的Constraint Class的代码
package custom.Annotation;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;
import play.Logger;
import java.util.regex.Pattern;
public class NameValidator extends AbstractAnnotationCheck<ValidName>
{
public final static String message="custom.message";
private static final String letter = "[a-zA-Z]";
public static final Pattern VALID_PATTERN = Pattern.compile(letter);
public static boolean isValidText(String userName) {
return VALID_PATTERN.matcher(userName).matches();
}
@Override
public void configure(ValidName annotation) {
setMessage(annotation.message());
}
@Override
public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context,
Validator validator) throws OValException {
try
{
if (valueToValidate == null) {
return false;
}
}catch (Exception e){
e.getMessage();
}
return` isValidText(valueToValidate.toString()`);
}
}
当我将@ValidName
应用于任何局部变量时,没有发生任何事情
我也无法调试该程序。有什么建议吗?
答案 0 :(得分:1)
您需要通过调用validate
库的oval validation
方法来使用椭圆验证。
@Autowired
@Qualifier("ovalValidator")
private Validator ovalValidator;
List<ConstraintViolation> violations = null;
violations = ovalValidator.validate(objectToValidate);