Kotlin data class and bean validation with container element constraints

前端 未结 2 1292
难免孤独
难免孤独 2021-02-05 09:06

With Bean Validation 2.0 it is possible to also put constraints on container elements.

I cannot get this to work with Kotlin data classes:

data class Som         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 09:23

    Starting Kotlin 1.3.70 and 1.4, this should be possible setting a specific compiler option: https://kotlinlang.org/docs/reference/whatsnew14.html#type-annotations-in-the-jvm-bytecode .

    On any previous version or any situation where this support is not sufficient, you have to write a custom validator.

    Example one for validating that a collection only contains hex strings:

    @Target(
        AnnotationTarget.FUNCTION,
        AnnotationTarget.PROPERTY_GETTER,
        AnnotationTarget.PROPERTY_SETTER,
        AnnotationTarget.FIELD,
        AnnotationTarget.ANNOTATION_CLASS,
        AnnotationTarget.CONSTRUCTOR,
        AnnotationTarget.VALUE_PARAMETER
    )
    @Retention(AnnotationRetention.RUNTIME)
    @MustBeDocumented
    @Constraint(validatedBy = [HexStringElementsValidator::class])
    annotation class HexStringElements(
        val message: String = "must only contain hex values",
        val groups: Array> = [],
        val payload: Array> = []
    )
    
    class HexStringElementsValidator : ConstraintValidator> {
    
        companion object {
            val pattern = "^[a-fA-F0-9]+\$".toRegex()
        }
    
        override fun isValid(value: Collection?, context: ConstraintValidatorContext?) =
            value == null || value.all { it is String && pattern.matches(it) }
    }
    

提交回复
热议问题