Javax Pattern注解验证以Type结尾的值失败问题求助
问题描述
需要实现输入值必须以"Type"结尾的验证,编写了正则表达式Type$并在Javax的@Pattern注解中使用,但传入"OccasionType"这类符合要求的值时验证失败,而该正则在regex101上测试正常。
相关代码:
@Pattern(regexp = REGISTRY_CONFIG_TYPE_FORMAT,message = REGISTRY_CONFIG_TYPE_ERROR) @ApiModelProperty(name = "registryConfigType", dataType = "String", value = "OccasionType", example = "OccasionType", required = true) private String registryConfigType;
常量定义:
REGISTRY_CONFIG_TYPE_FORMAT = "Type$"
收到的报错日志:
Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.macys.registry.dataobject.v1.response.RegistryAppResponse<java.lang.Object> com.macys.registry.controller.RegistryConfigController.updateConfig(com.macys.registry.dataobject.v1.request.UpdateRegistryConfigRequest): [Field error in object 'updateRegistryConfigRequest' on field 'registryConfigType': rejected value [OccasionType]; codes [Pattern.updateRegistryConfigRequest.registryConfigType,Pattern.registryConfigType,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [updateRegistryConfigRequest.registryConfigType,registryConfigType]; arguments []; default message [registryConfigType],[Ljavax.validation.constraints.Pattern$Flag;@20999237,Type$]; default message [Registry Config Type Should Not Be Null And Should End With [Type]]] ]
问题原因与解决办法
问题出在Javax的@Pattern注解默认要求整个字符串完全匹配正则表达式,而非部分匹配。你编写的Type$仅会匹配刚好等于"Type"的字符串,而"OccasionType"前面包含其他字符,自然无法通过验证。而regex101默认采用部分匹配模式,所以测试时能匹配到结尾的"Type",导致你误以为正则没问题。
解决办法很简单,修改正则表达式,允许字符串前面存在任意字符:
将常量定义改为:
REGISTRY_CONFIG_TYPE_FORMAT = ".*Type$"
.*表示匹配任意数量(包括0个)的任意字符Type$确保字符串以"Type"结尾
如果需要更严谨的匹配(明确从字符串开头到结尾),也可以写成:
REGISTRY_CONFIG_TYPE_FORMAT = "^.*Type$"
内容的提问来源于stack exchange,提问作者divine_rythm
相关产品推荐
相关产品推荐

