简体   繁体   English

使用@Enumerated批注验证字段

[英]Validate field with @Enumerated annotation

I need to validate an entity with the @Valid annotation. 我需要使用@Valid批注验证实体。 A field of my entity can take a set of numerical values and I thought to use the @Enumerated annotation. 我实体的一个字段可以采用一组数值,我想使用@Enumerated批注。 It may take the values ​​5, 10, 15, 20 and 30. Can I handle it with that annotation? 它可能取值为5、10、15、20和30.我可以使用该注释来处理它吗? How? 怎么样?

Thanks! 谢谢!

UPDATE 更新

I solved my issue in the following way: 我通过以下方式解决了我的问题:

I created an annotation @ValidateIntegerSet 我创建了一个注释@ValidateIntegerSet

@Documented  
@Retention(RetentionPolicy.RUNTIME)  
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.ANNOTATION_TYPE})  
@Constraint(validatedBy=IntegerSet.class)
public @interface ValidateIntegerSet {

int[] acceptedValues();

String message() default "Il valore inserito non è tra quelli ammissibili"; 

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

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

I created an class IntegerSet to perform the validation 我创建了一个IntegerSet类来执行验证

public class IntegerSet implements ConstraintValidator<ValidateIntegerSet, Integer> {  

private List<Integer> valueList;

@Override
public void initialize(ValidateIntegerSet constraintAnnotation) {
    valueList = new ArrayList<Integer>();
    for(int val : constraintAnnotation.acceptedValues()) {
        valueList.add(Integer.valueOf(val));
    }
}

@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
    if(!valueList.contains(value)) {
        return false;
    }
    return true;
}
}

I have used the new annotation in the following way: 我已经通过以下方式使用了新的注释:

@ValidateIntegerSet(acceptedValues={5, 10, 15, 20, 30})

@Enumerated @枚举

is for sure something that won't work. 肯定是行不通的。 You need custom validator for that, as there is no build-in validator for that. 为此,您需要自定义验证器,因为没有内置验证器。 You could try to use @Pattern 可以尝试使用@Pattern

Custom Validator 自定义验证器

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

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