简体   繁体   English

使用Java中的注释验证字符串列表

[英]Validating a list of strings using annotations in Java

In my class I have an attribute with List of Short Codes: List[ShortCode] . 在我的课堂上,我有一个带有短代码List[ShortCode]的属性: List[ShortCode]

I have a custom defined annotations for valid short code as ValidShortCode . 我为有效的短代码自定义定义了注释,如ValidShortCode

Code for this implementation: 此实现的代码:

@Target({ METHOD, FIELD, ANNOTATION_TYPE })

@Retention(RUNTIME)

@Constraint(validatedBy = ShortCodeValidator.class)

@Documented

public @interface ValidShortCode {

String message() default "{ValidShortCode.message}";

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

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

}

public class ShortCodeValidator implements ConstraintValidator<ValidShortCode, String> {
private static final int MIN_LENGTH = 1;
private static final int MAX_LENGTH = 15;
private static final int EMPTY_LENGTH = 0;
@Override
public void initialize(ValidShortCode shortCode) {
    // TODO Auto-generated method stub
}

@Override
public boolean isValid(final String value,
        final ConstraintValidatorContext constraintContext) {
    boolean valid = false;
    if (null == value || value.trim().length() == EMPTY_LENGTH) {
        valid = true;
    }
    else if((value.trim().length() >= MIN_LENGTH)&&(value.trim().length() <= MAX_LENGTH)){
        valid = value.matches("([A-Za-z0-9])+");
    }
    return valid;
}
}

And for validating the above List[ShortCode] I am writing another custom annotation for this List of short codes. 为了验证上面的List[ShortCode]我正在为此简短代码列表编写另一个自定义注释。

I have an idea to validate the short code again in this custom annotation but it is code duplication. 我有一个想法可以在此自定义批注中再次验证短代码,但这是代码重复。

In my custom annotation for validating the List of Short Codes, I have this: 在我的用于验证短代码列表的自定义注释中,我具有以下内容:

public class ListValidator  implements ConstraintValidator<ValidList, List<String>> {
private static final int EMPTY_SIZE = 0;

@Override
public void initialize(ValidList validList) {
    // TODO Auto-generated method stub
}

@Override
public boolean isValid(final List<String> value,
        final ConstraintValidatorContext constraintContext) {
    boolean valid = false;
    if (null == value || value.size() == EMPTY_SIZE) {
        valid = true;
    }
    else {
        for(String shortCode: value) {
            // Implementing the same code as done for the previous short code annotation
        }
    }
    return valid;
}
}

Can some one help me in letting me know how I can reuse the custom defined annotation ValidShort or any other efficient method to solve this situation? 有人可以帮助我让我知道如何重用自定义定义的注释ValidShort或任何其他有效的方法来解决这种情况吗?

Thanks. 谢谢。

You can do it without custom validators. 您可以在没有自定义验证程序的情况下进行操作。
Wrap the short code inside a class and validate the String either on a getter or on the member itself: 将简短代码包装在类中,并在getter或成员本身上验证String:

class ShortCode {  
    private String value;

    ShortCode(String value) {
       this.value = value.trim();
    }

    @Pattern(regexp="PATTERN")
    @Size(min=1, max=15)
    String getValue() {
        return value;
    }
}

Add @Valid annotation before the list, this way all elements in the List will be validated according to the validation defined above: 在列表之前添加@Valid批注,这样将根据上面定义的验证来验证List中的所有元素:

@Valid
List<ShortCode> shortCodesList;

Nothing prevents you from using the same validator you've implemented already: 没有什么可以阻止您使用已经实现的同一验证器:

@Override
public boolean isValid(final List<String> value,
        final ConstraintValidatorContext constraintContext) {
    boolean valid = true;
    if (null != value && value.size() != EMPTY_SIZE) {
        ShortCodeValidator validator = new ShortCodeValidator();    
        for(String shortCode: value) {
            result &= validator.isValid(shortCode);
        }
    }
    return valid;
} 

This example assumes that list validation should fail if at least one of list items is invalid. 本示例假定如果至少一个列表项无效,则列表验证应失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM