Home > front end >  Javax Pattern annotation failing for correct values
Javax Pattern annotation failing for correct values

Time:10-12

I need to use validation where input value should end with "Type" So I came up with Type$ regex, but it is failing for correct values. Here is how I am using this in Pattern annotation in my code

@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;

the constant value

REGISTRY_CONFIG_TYPE_FORMAT = "Type$"

when I am passing value like : OccasionType, I am getting the error message. But on regex101 it's working fine. Not sure where is the problem.

enter image description here

following is the error log which I am getting

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]]] ]

CodePudding user response:

It may not be 100% clear from the javadoc, but the regexp must match. In other words, the entire input must be captured by the regexp. A simple fix: .*Type. Note that the $ is unnecessary, as that's already implied by the matching.

Your regex would be valid if find where used instead of match.

CodePudding user response:

Try this for your case

REGISTRY_CONFIG_TYPE_FORMAT= ".*Type$";

CodePudding user response:

Try changing you constant to:

REGISTRY_CONFIG_TYPE_FORMAT = "\\w*Type\\b";

From RegExr:

\w  Word. Matches any word character (alphanumeric & underscore).
  *  Quantifier. Match 0 or more of the preceding token.
T  Character. Matches a "T" character (char code 84). Case sensitive.
y  Character. Matches a "y" character (char code 84). Case sensitive.
p  Character. Matches a "p" character (char code 84). Case sensitive.
e  Character. Matches a "e" character (char code 84). Case sensitive.
\b  Word boundary. Matches a word boundary position between a word character and non-word character or position (start / end of string).

Hope this will help.

  • Related