Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To validate more than one field at once, use an annotation on type-Level and write a custom Validator that checks all String fields using your REGEXP.</p> <p>Edit: Provide example. This is quite ugly, because it uses Reflection and violates security, but maybe it gives you a general idea. If you dont use "object" but a concrete class or interface, you could possibly have success with regular getters.</p> <p>The Class under Test (and the Runner)</p> <pre><code> import javax.validation.Validation; import javax.validation.Validator; import validation.AllStringsRegex; @AllStringsRegex(value="l") public class UnderValidation { String a; String b; public static void main(String... args) { UnderValidation object = new UnderValidation(); object.a = "hello"; object.b = "world"; Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); System.out.println(validator.validate(object)); } } </code></pre> <p>My Annotation:</p> <pre><code>@Target( { TYPE, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = AllStringsRegexValidator.class) @Documented public @interface AllStringsRegex { String message() default "String not regex"; String value() default ""; Class&lt;?&gt;[] groups() default {}; Class&lt;? extends Payload&gt;[] payload() default {}; } </code></pre> <p>My Validator</p> <pre><code>public class AllStringsRegexValidator implements ConstraintValidator&lt;AllStringsRegex, Object&gt; { private Pattern pattern = null; @Override public void initialize(AllStringsRegex annotation) { pattern = Pattern.compile(annotation.value()); } @Override public boolean isValid(Object object, ConstraintValidatorContext ctx) { for (Field f : object.getClass().getDeclaredFields()) { if (f.getType().equals(String.class)) { try { f.setAccessible(true); String value = (String)f.get(object); if (!pattern.matcher(value).find()) { return false; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return true; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload