Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Pattern From validation.api want to configure all the pattern in one property file

Can anybody help me of configuring the @Pattern annotation from validation-api.1.1.jar

@Pattern(regex = "PATTERN")this configuration is simple but my requirement is to have a central file consisting of all the pattern with key and value as pattern .i.e properties file.

Please your help would be appreciated.

like image 666
NIKET BHANDARY Avatar asked Oct 27 '25 07:10

NIKET BHANDARY


2 Answers

Unfortunately, it isn't really feasible to have a properties file, per se, that contains your pattern regexes for use with the @Pattern annotation because Java requires that annotations use compile-time constants. These compile-time regexes cannot be retrieved from a properties file, because a properties file can't be parsed at compile time; properties files are parsed at runtime.

That being said, you can keep all of your compile-time constant regex patterns in a central class or interface. For example, consider the following code:

public class FooClass {
  @Pattern(regex = Patterns.FOO_PATTERN)
  public void foo() {}
}

public class BarClass {
  @Pattern(regex = Patterns.BAR_PATTERN)
  public void bar() {}
}

public class Patterns {
  public static final String BAR_PATTERN = "bar?";
  public static final String FOO_PATTERN = "foo*";
}

As you can see, you can have a common class where you keep all of your regex pattern strings. I hope that helps.

like image 104
entpnerd Avatar answered Oct 29 '25 21:10

entpnerd


As mentioned in the other answer, its not possible to make the pattern configurable in application.properties for @Pattern. The best approach to make the pattern configurable via application.properties is by writing a custom annotation like below:

@Documented
@Target({ElementType.PARAMETER})
@Constraint(validatedBy = DynamicPatternValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface DynamicPattern {

    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

You then have to write the custom validator to do the validation:

import javax.validation.ConstraintValidatorContext;

import static org.apache.commons.lang3.StringUtils.isEmpty;

    public class DynamicPatternValidator implements ConstraintValidator<DynamicPattern, String> {

    @Value("${validation.email.pattern}")
    private String pattern;
    
        public boolean isValid(String chars, ConstraintValidatorContext context) {
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(pattern);
            context.buildConstraintViolationWithTemplate("Must match pattern " + getPattern())
                    .addConstraintViolation().disableDefaultConstraintViolation();
            return pattern.matcher(chars).matches();
        }
    }
like image 30
Yuvi Avatar answered Oct 29 '25 22:10

Yuvi