How to validate UUID with bean validation in Kotlin

A small bean validation constraint annotation in Kotlin for UUIDs

UUID wordmark, the identifier format this Kotlin validator checks
UUID Logo

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 it for today! ✨


Go Further

How to implement input validation with NestJS
Learn how to validate incoming data with NestJS
How to write integration tests for a GraphQL API with Spring Boot and Kotlin
How to write integration tests for a GraphQL API using Spring Boot 2.x and Kotlin
Creating custom class-validator validators for MomentJS
Learn how to custom validators for MomentJS

Want to go deeper?

Knowii Community - Master Knowledge Management + AI | From €4.99/month
Join 400+ members mastering Knowledge Management AND AI. Community + Courses + Tools integrated. €500+ value in Knowledge Master tier.


About Sébastien

I'm Sébastien Dubois, and I'm on a mission to help knowledge workers escape information overload. After 20+ years in IT and seeing too many brilliant minds drowning in digital chaos, I've decided to help people build systems that actually work. Through the Knowii Community, my courses, products & services and my Website/Newsletter, I share practical and battle-tested systems.

I write about Knowledge Work, Personal Knowledge Management, Note-taking, Lifelong Learning, Personal Organization, Productivity, and more. I also craft lovely digital products and tools.

If you want to follow my work, then become a member and join our community.

Ready to get to the next level?

If you're tired of information overwhelm and ready to build a reliable knowledge system:

Found this valuable? Share it with someone who needs it.

Join 6,000+ readers. Get practical systems for knowledge & AI. Free.

Subscribe ✨

Free: Knowledge System Checklist

A clear roadmap to building your own knowledge system. Subscribe and get it straight to your inbox.

6,000+ readers. No spam. Unsubscribe anytime.