简体   繁体   English

如何为 `javax.validation.constraints` 注释添加自定义验证器?

[英]how add custom validator for `javax.validation.constraints` annotation?

I have implemented validation for Long field and @PastOrPresent validation我已经为Long字段和@PastOrPresent验证实现了验证

public class PastOrPresentValidator implements ConstraintValidator<PastOrPresent, Long>{
    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        return value <= System.currentTimeMillis();
    }
}

public class MyDto {
    @PastOrPresent
    Long timestamp;    
}

And got error:并得到错误:

HV000030: No validator could be found for constraint 'javax.validation.constraints.PastOrPresent' validating type 'java.lang.Long'. Check configuration for 'push.dto.timestamp'

But when I create custom annotation like @PastOrPresentLong and use same validator code everything works.但是,当我创建像@PastOrPresentLong这样的自定义注释并使用相同的验证器代码时,一切正常。

Is there a way to add custom validator for javax.validation.constraints annotation?有没有办法为javax.validation.constraints注释添加自定义验证器?

Just implementing the ConstraintValidator interface isn't enough for your new validator to work. 仅实现ConstraintValidator接口不足以使新的验证程序正常工作。 It should be somehow registered so that BeanValidation provider knows about it. 应该以某种方式注册它,以便BeanValidation提供程序知道它。 This can be done via XML (see for more info here ): 这可以通过XML进行(详情参见这里 ):

<constraint-mappings
        xmlns="http://xmlns.jcp.org/xml/ns/validation/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/validation/mapping
            http://xmlns.jcp.org/xml/ns/validation/mapping/validation-mapping-2.0.xsd"
        version="2.0">
    <!-- anything else -->
    <constraint-definition annotation="javax.validation.constraints.PastOrPresent">
        <validated-by include-existing-validators="true">
            <value>org.mycompany.PastOrPresentLongValidator</value>
        </validated-by>
    </constraint-definition>
</constraint-mappings>

Then if you are using Hibernate Validator as BeanValidation provider you also have two more options - use service loader or programmatic definition. 然后,如果您将Hibernate Validator用作BeanValidation提供程序,则还有另外两个选项-使用服务加载程序或编程定义。 Using Service loader is the easiest way of adding new validator. 使用服务加载程序是添加新验证程序的最简单方法。 All you need to do is create a META-INF/services/javax.validation.ConstraintValidator file and add a FQCN of your validator to it. 您需要做的就是创建一个META-INF/services/javax.validation.ConstraintValidator文件,并向其中添加验证器的FQCN。 See detailed examples in this post under section "Use standard constraints for non standard classes" or in the doc . 见详细的例子在这个职位根据第“使用非标类标准限制”或文档 With programmatic approach you would have to do something like: 使用编程方法,您将必须执行以下操作:

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
        .constraintDefinition( PastOrPresent.class )
        .validatedBy( PastOrPresentLongValidator.class );

And then add this constraint mapping to your configuration and create a validator from it: 然后将此约束映射添加到您的配置中,并从中创建一个验证器:

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

But as I mentioned earlier - Service Loader is the easiest and quickest way to go. 但是正如我前面提到的那样,Service Loader是最简单,最快的方法。

Simpler Approach更简单的方法

A simpler declarative approach to linking the annotation to the validator is to specify the linkage through a Constraint(validatedBy) annotation.将注释链接到验证器的更简单的声明方法是通过 Constraint(validatedBy) 注释指定链接。

@Retention(RUNTIME)
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Constraint(validatedBy = PastOrPrsentValidator.class)
public class PastOrPresentValidator implements ConstraintValidator<PastOrPresent, Long>{
...

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

相关问题 Java 中的 json 验证器 - 使用 javax.validation.constraints - json validator in Java - using javax.validation.constraints 结合自定义 ConstraintValidator 的 javax.validation.constraints 注释 - Annotations from javax.validation.constraints in combination with custom ConstraintValidator javax.validation.constraints中的转义序列无效 - Invalid escape sequencein javax.validation.constraints 原始布尔值的 javax.validation.constraints? - javax.validation.constraints for primitive boolean? 来自 javax.validation.constraints 的注释不起作用 - Annotations from javax.validation.constraints not working 关注点重复javax.validation.constraints和javax.persistence.Column - Duplication of concerns javax.validation.constraints and javax.persistence.Column 以编程方式“关闭”bean验证(javax.validation.constraints) - “Turn off” bean validation programmatically (javax.validation.constraints) 来自javax.validation.constraints的注释不起作用(忽略) - Annotations from javax.validation.constraints not working (ignored) Swagger软件包javax.validation.constraints不存在 - Swagger package javax.validation.constraints does not exist 是否可以将 spring boot @Value 与 javax.validation.constraints 结合使用? - Is it possible to combine spring boot @Value with javax.validation.constraints?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM