Skip to content

How to validate UUID with bean validation in Kotlin

Sébastien Dubois /

1 min read

Here’s a quickie: a small bean validation constraint annotation in Kotlin for UUIDs

Kotlin UUID Bean Validation Constraint

import javax.validation.Constraint
import javax.validation.Payload
import javax.validation.constraints.NotBlank
import javax.validation.constraints.Pattern
import kotlin.reflect.KClass

const val UUID_REGEXP = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"

/**
 * Validation constraint for {@link UUID}s.
 * Reference: https://stackoverflow.com/questions/37320870/is-there-a-uuid-validator-annotation
 */
@Target(AnnotationTarget.FIELD)
@Constraint(validatedBy = [])
@Retention(AnnotationRetention.RUNTIME)
@NotBlank
@Pattern(regexp = UUID_REGEXP)
annotation class UUID(
        val message: String = "{invalid.uuid}",
        val groups: Array<KClass<*>> = [],
        val payload: Array<KClass<out Payload>> = []
)

That’s all folks!

About Sébastien

Hello everyone! I'm Sébastien Dubois. I'm an author, founder, and CTO. I write books and articles about software development & IT, personal knowledge management, personal organization, and productivity. I also craft lovely digital products 🚀

If you've enjoyed this article and want to read more like this, then subscribe to my newsletter, check out my PKM Library and my collection of books about software development 🔥.

You can follow me on Twitter 🐦

If you want to discuss, then don't hesitate to join one of my communities: the Software Crafters community, the Personal Knowledge Management community, and the focusd Productivity community
Get Sébastien's free weekly newsletter. Read by hundreds of people to explore and stay up to date on learning, personal knowledge management, personal organization, software development, and bootstrapping