简体   繁体   中英

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?

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 )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM