问题描述
在验证我的请求参数时,我正在做NonNull检查,但是现在我想阻止某些类型的模式。
@Prototype
public class MyObj {
@NotBlank(message="Error: id cannot be null")
@JsonProperty("id")
private String id;
}
现在我必须阻止ID匹配以下任何模式的请求
(\*\s+(\w+)\s+\*)
((\w+)\:(\d+)\/(\d+))
我知道我可以加入@Pattern(regexp =
来允许特定的模式,但是不确定如何阻止特定的模式。并进行多种模式验证。
解决方法
您可以在@Pattern批注中使用negative lookahead来排除两个指定的模式。
^(?!(\*\s+(\w+)\s+\*)$)(?!((\w+)\:(\d+)\/(\d+))$).*
,
如果您仍然打算通过注释进行操作,则可以创建自己的注释。 在这里使用micronaut作为示例:
@Prototype
public class MyObj {
@NotAllowedPattern(values={onePattern,secondPattern})
@JsonProperty("id")
private String id;
}
@Singleton
ConstraintValidator<NotAllowedPattern,String> notAllowedPattern() {
return (value,annotationMetadata,context) -> {
// patterns should be mandatory as per annotation
Optional<String[]> annotationPatterns = annotationMetadata.stringValue("values");
String[] patterns = annotationPatterns.get();
// if a single pattern from the not allowed matches this should return false
// and raise a <code>ConstraintViolationException</code> which results into error message.
return doesNotMatchAllPatterns(value,patterns);
};
}