JSR-303 Bean Validation注释多个字段 [英] JSR-303 Bean Validation annotate multiple fields

查看:193
本文介绍了JSR-303 Bean Validation注释多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始测试JSR-303 Bean验证,并且想知道是否有可能。我们的app中有一个默认的正则表达式,用于所有String字段。如果我想使用bean验证来应用它,我想我需要在表单对象中注释每个字段。

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;

是否可以在一次点击中将@Pattern应用于所有字符串(或某些字段)?我们在Weblogic 10.3.4上使用Hibernate实现,JSF2.0作为前端。验证应独立于视图,因为我可能会从网络服务进入。

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.

推荐答案

要一次验证多个字段,在类型级别上使用注释并编写一个自定义Validator,使用您的REGEXP检查所有String字段。

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.

编辑:提供示例。这非常难看,因为它使用Reflection并违反安全性,但也许它会给你一个大致的想法。如果你不使用object但是使用具体的类或接口,你可能会成功使用常规getter。

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.

测试中的类(和Runner)

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

我的注释:

@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 {};
}

我的验证员

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

这篇关于JSR-303 Bean Validation注释多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆