Skip to content

Instantly share code, notes, and snippets.

@vbsteven
Created April 8, 2019 16:27
Show Gist options
  • Save vbsteven/b2311c51b2686cbacf037b0fffb2eb06 to your computer and use it in GitHub Desktop.
Save vbsteven/b2311c51b2686cbacf037b0fffb2eb06 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()
}
}
@pmarquez
Copy link

pmarquez commented Mar 4, 2023

Thanks for sharing this Kotlin gist. They are hard to come by and deeply appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment