Skip to content

Instantly share code, notes, and snippets.

@dharamgollapudi
Forked from vbsteven/Validators.kt
Created October 3, 2021 21:06
Show Gist options
  • Save dharamgollapudi/bc5d72bf23b0b781514b10de3aa7d6e8 to your computer and use it in GitHub Desktop.
Save dharamgollapudi/bc5d72bf23b0b781514b10de3aa7d6e8 to your computer and use it in GitHub Desktop.
Custom Spring annotation and validator in Kotlin
package io.license.core.validation
import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import javax.validation.Payload
import kotlin.reflect.KClass
@Target(AnnotationTarget.FIELD)
@MustBeDocumented
@Constraint(validatedBy = [NullableNotBlankValidator::class])
annotation class NullableNotBlank(
val message: String = "{javax.validation.constraints.NotBlank.message}",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
class NullableNotBlankValidator : ConstraintValidator<NullableNotBlank, String> {
override fun isValid(value: String?, context: ConstraintValidatorContext?): Boolean {
if (value == null) return true
return value.isNotBlank()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment