Created
April 8, 2019 16:27
-
-
Save vbsteven/b2311c51b2686cbacf037b0fffb2eb06 to your computer and use it in GitHub Desktop.
Custom Spring annotation and validator in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
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
Hi @vbsteven,
thanks for sharing your Validator and Annotation.
I changed the
isValid
Method inNullableNotBlankValidator
a bit.The related tests stay successful