I want to add validator annotation contains value in list.(String, Int etc..)

Viewed 28

I want to use generics to validate if a value is contained within a list. You can use a @Pattern annotation, but I'm trying to create a more concise annotation. How can i complete it?

@field:Contains(values = [1,2])
val type: Int,

@field:Contains(values = ["1","2"])
val type2: String

@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [ContainsValidator::class])
annotation class Contains(
    val values: Array<T> = [],
    val message: String = "{javax.validation.constraints.AssertFalse.message}",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
)

class ContainsValidator<T> : ConstraintValidator<Contains, T> {
    private val acceptedValues: MutableList<T> = mutableListOf()

    override fun initialize(constraintAnnotation: Contains) {
        super.initialize(constraintAnnotation)
        acceptedValues.addAll(KClass<T> constraintAnnotation.values )
    }

    override fun isValid(value: T, context: ConstraintValidatorContext): Boolean {
        return if (value == null) {
            true
        } else {
            acceptedValues.contains(value)
        }
    }
}
0 Answers
Related