Search code examples
javaregexjavabeansbean-validation

Bean Validation for exact string match


  1. I want to validate a string for exact match in bean validation. Should I use @Pattern or is there a different method to do so?
  2. If @Pattern is the way to go, what is the regex?
  3. Can I use two @Pattern annotation for two different groups on a same field?

Solution

  • I want to validate a string for exact match in bean validation. Should I use @Pattern or is there a different method to do so?

    You could either use @Pattern or implement a custom constraint very easily:

    @Documented
    @Constraint(validatedBy = MatchesValidator.class)
    @Target({ METHOD, CONSTRUCTOR, PARAMETER, FIELD })
    @Retention(RUNTIME)
    public @interface Matches {
        String message() default "com.example.Matches.message";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
        String value();
    }
    

    With the validator like this:

    public class MatchesValidator implements ConstraintValidator<Matches, String> {
    
        private String comparison;
    
        @Override
        public void initialize(Matches constraint) {
            this.comparison = constraint.value();
        }
    
        @Override
        public boolean isValid(
            String value,
            ConstraintValidatorContext constraintValidatorContext) {
    
            return value == null || comparison.equals(value);
        }
    }
    

    If @Pattern is the way to go, what is the regex?

    Basically just the string you want to match, you only need to escape special characters such as [\^$.|?*+(). See this reference for more details.

    Can I use two @Pattern annotation for two different groups on a same field?

    Yes, just use the the @Pattern.List annotation:

    @Pattern.List({
        @Pattern( regex = "foo", groups = Group1.class ),
        @Pattern( regex = "bar", groups = Group2.class )
    })