交叉字段自定义约束注释不起作用 [英] Cross Field Custom constraint annotation not working

查看:76
本文介绍了交叉字段自定义约束注释不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 ContactTypeName 的下拉字段,其中包含电话号码,电子邮件等的值和名为的联系人字段 >我想验证输入字段的有效电子邮件地址,如果下拉列表电子邮件被选中...





i有以下bean

  @ FieldMatch.List({
@FieldMatch(first =contactDetail,second =contectTypeName,message =请输入一个有效的电子邮件地址)
public class Contact {
private int contactId = 0;
@NotNull(message =请选择一个联系人类型)
private Integer contectTypeId;
private String contectTypeName;
@NotNull(message =请指定联系人详细信息)
private String contactDetail;
}

我尝试创建一个自定义约束来验证 contactTypeName 字段的值为电子邮件地址 <>,​​那么使用> contactDetail 字段作为电子邮件正则表达式/ p>

我对自定义约束具有以下代码:

  @Target {TYPE,ANNOTATION_TYPE,METHOD,FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch
{
字符串消息()默认{constraints.fieldmatch};

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

类<?扩展了Payload> [] payload()default {};
$ b $ / **
* @return第一个字段
* /
字符串first();

/ **
* @return第二个字段
* /
字符串second();

/ **
*定义了几个< code> @ FieldMatch< / code>同一元素上的注解
*
* @see FieldMatch
* /
@Target({TYPE,ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface列表
{
FieldMatch [] value();


$ / code>

以及像

$ b $这样的验证器b

  public class FieldMatchValidator implements ConstraintValidator< FieldMatch,Object> 
{
private String firstFieldName;
private String secondFieldName;

私人图案图案;
私人匹配器匹配器;


private static final String EMAIL_PATTERN =
^ [_A-Za-z0-9 -\\\ + +] +(\\。[_A-Za -Z0-9 - ] +)* @
+[A-Za-z0-9 - ] +(\\。[A-Za-z0-9] +)*(\\\ \\ [A-ZA-Z] {2,})$。



@Override
public void initialize(final FieldMatch constraintAnnotation)
{
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
pattern = Pattern.compile(EMAIL_PATTERN);


$ @Override
public boolean isValid(final Object value,final ConstraintValidatorContext context)
{
try
{
final Object firstObj = BeanUtils.getProperty(value,firstFieldName); //电子邮件地址
final Object secondObj = BeanUtils.getProperty(value,secondFieldName); // contactType的值

System.out.println((String)firstObj);
System.out.println((String)secondObj); (((String)firstObj ==||(String)firstObj == null)&&(String)secondObj!=Email){
return true ;
} else {
matcher = pattern.matcher((String)firstObj);
return matcher.matches();

}

//返回firstObj == null&& secondObj == null || firstObj!= null&& firstObj.equals(secondObj);
}
catch(final exception ignore)
{
//忽略
}
返回true;
}
}

问题在于它没有在表单发布... im使用 Prime Faces 模型对话框,其中要验证的bean被呈现



REF:使用Hibernate Validator进行交叉字段验证(JSR 303)



期待您的建议和指导

解决方案

JSF 2.0不支持交叉字段尚未验证 https://hibernate.onjira.com/browse/BVAL-214



以使其工作或者使用像 seamfaces 或手动调用验证,如

  Validator validator = Validation.buildDefaultValidatorFactory()。getV alidator(); 
Set< ConstraintViolation<联系人>> violation = validator.validate(contact);


i have a dropdown field named ContactTypeName which have the values like phone, email etc and an input field named Contact i want to validate the input field for valid email address if the dropdown value Email is selected...


i have the following bean

@FieldMatch.List({    
    @FieldMatch(first = "contactDetail", second = "contectTypeName", message = "Please Enter a valid email address")
})
public class Contact {
    private int contactId = 0;
    @NotNull(message="Please Select a Contact Type")
    private Integer contectTypeId;
    private String contectTypeName;
    @NotNull(message="Please Specify Contact Details")
    private String contactDetail;   
}

im trying to create a custom constraint which will validate the contactDetail field against an email regex if the contactTypeName field will have the value Email

i have the following code for the custom constraint

@Target({TYPE, ANNOTATION_TYPE,METHOD, FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch
{
    String message() default "{constraints.fieldmatch}";

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

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

    /**
     * @return The first field
     */
    String first();

    /**
     * @return The second field
     */
    String second();

    /**
     * Defines several <code>@FieldMatch</code> annotations on the same element
     *
     * @see FieldMatch
     */
    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
            @interface List
    {
        FieldMatch[] value();
    }
}

and the validator like

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
    private String firstFieldName;
    private String secondFieldName;

    private Pattern pattern;
    private Matcher matcher;


    private static final String EMAIL_PATTERN = 
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";



    @Override
    public void initialize(final FieldMatch constraintAnnotation)
    {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
        pattern = Pattern.compile(EMAIL_PATTERN);

    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context)
    {
        try
        {           
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);//email address
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);//value of the contactType

            System.out.println((String) firstObj);
            System.out.println((String) secondObj);

            if(((String) firstObj == "" || (String) firstObj == null ) && (String) secondObj != "Email"){
                return true;
            }else{
                matcher = pattern.matcher((String) firstObj);
                return matcher.matches();

            }

            //return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception ignore)
        {
            // ignore
        }
        return true;
    }
}

the problem is that its not firing on the form post... im using Prime Faces model dialog in which the bean to be validated is rendered

REF: Cross field validation with Hibernate Validator (JSR 303)

looking forward to your suggestions and guidance

解决方案

JSF 2.0 does not support cross field validation yet https://hibernate.onjira.com/browse/BVAL-214

to make it work either use a library like seamfaces or call the validation manually like

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<Contact>> violations = validator.validate(contact);

这篇关于交叉字段自定义约束注释不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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