Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 897
Kevin Rave Avatar asked Nov 15 '25 14:11

Kevin Rave


1 Answers

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 )
})
like image 123
Gunnar Avatar answered Nov 18 '25 04:11

Gunnar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!