【问题标题】:Validate request body not equal to a pattern验证请求正文不等于模式
【发布时间】:2020-09-01 14:44:21
【问题描述】:
在验证我的请求参数时,我正在执行 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 = 以允许特定模式,但不确定如何阻止特定模式。并且还可以进行多种模式验证。
【问题讨论】:
标签:
java
spring
micronaut
【解决方案1】:
您可以在@Pattern 注释中使用negative lookahead 来排除两个指定的模式。
^(?!(\*\s+(\w+)\s+\*)$)(?!((\w+)\:(\d+)\/(\d+))$).*
【解决方案2】:
如果您仍打算通过注释来实现,您可以创建自己的。
在此处使用 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);
};
}