java验证约束不适用于字符串列表

eyh26e7m  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(198)

我已经创建了一个自定义验证器来验证字符串。它对单个字符串有效,但对字符串列表无效。这就是我迄今为止所尝试的:

@Get("/test1")
public String test1(
       @QueryValue(value = "ids") List<@DurationPattern String> ids) { //NOT WORKING
    return "not working";
}

@Get("/test2")
public String test2(
        @QueryValue(value = "id") @DurationPattern String id){ //WORKS
    //it does not get here which is what I want.
    return "done";
}

我的 @DurationPattern 代码:

package my.package;

import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import my.package.DurationPattern.List;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE, TYPE, LOCAL_VARIABLE, PACKAGE, TYPE_PARAMETER, MODULE })
@Repeatable(List.class)
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { })
public @interface DurationPattern {

    String message() default "invalid duration ({validatedValue})";

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE, TYPE, LOCAL_VARIABLE, PACKAGE, TYPE_PARAMETER, MODULE})
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        DurationPattern[] value();
    }
}

实际验证程序:

package my.package;

import io.micronaut.context.annotation.Factory;
import io.micronaut.validation.validator.constraints.ConstraintValidator;

import javax.inject.Singleton;

@Factory
public class MyValidatorFactory {

    @Singleton
    ConstraintValidator<DurationPattern, CharSequence> durationPatternValidator() {
        return (value, annotationMetadata, context) -> {
            System.out.println("Please Print!!! It doesn't for Strings within List");
            return value == null || value.toString().matches("^PT?[\\d]+[SMHD]{1}$");
        };
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题