JSR-303 Bean Validation annotate multiple fields

白昼怎懂夜的黑 提交于 2019-12-03 23:07:29

问题


I've just started testing JSR-303 Bean validation and was wondering if something was possible. We have a default regular expression in our app for all String fields. If I want to apply this using bean validation I think I need to annotate each field within my form object.

@Pattern(regexp = REG_EXP)
private String aString;

@Pattern(regexp = REG_EXP)
private String anotherString;

Is it possible to apply the @Pattern to all Strings (or certain fields) in one hit? We're using the Hibernate implementation on Weblogic 10.3.4 with JSF2.0 as the front end. Validation should be independent of view as I may be coming in from a webservice.


回答1:


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.

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.

The Class under Test (and the Runner)

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

My Annotation:

@Target( { TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = AllStringsRegexValidator.class)
@Documented
public @interface AllStringsRegex {
    String message() default "String not regex";
    String value() default "";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

My Validator

public class AllStringsRegexValidator implements ConstraintValidator<AllStringsRegex, Object> {
    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;
    }
}



回答2:


I didnt use but java supporting scripting in server side using grovvy ,javascript.. .You can check @ScriptAssert(lang = "javascript", script =_this.startDate.before(_this.endDate) scripting annotation which is hibernate annotation.



来源:https://stackoverflow.com/questions/9804009/jsr-303-bean-validation-annotate-multiple-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!