Skip to Content
Course content

249: Input Validation Patterns in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once worked on a project where we let users set their own custom handles for their profiles. It seemed simple enough: just a string field in the database. One afternoon, our URL generator started throwing 500 errors for a handful of users. It turned out one clever user had set their handle to a single whitespace character. Our database accepted it, our basic "is not null" check passed, but the URL builder crashed because it tried to trim the handle into non-existence before appending it to the domain. It was a classic case of "shallow validation"—checking that the data exists, but not that it actually makes sense for the business logic.

Fail-Fast with Require and Check

In Kotlin, the most immediate way to stop "garbage in" from polluting your system is by using the require and check standard library functions. I see a lot of developers writing verbose if (x == null) throw IllegalArgumentException(...) blocks, but that's just noise. You can condense that into a single, readable line.

Use require() when you are validating arguments passed into a function. If the condition is false, it throws an IllegalArgumentException. It's the "you gave me bad data" signal. On the other hand, use check() to verify the internal state of your object. If check() fails, it throws an IllegalStateException, which effectively says, "the data might be fine, but the system is in a state where this operation is impossible."

fun updateUserAge(age: Int) {
    // Fail fast: don't even let the code proceed if the age is impossible
    require(age in 0..120) { "Age must be between 0 and 120, but was $age" }
    
    // Imagine we have a state check to ensure the account is active
    check(this.isActive) { "Cannot update age for an inactive account" }
    
    this.age = age
}

The trailing lambda in these functions is where you put your error message. It's lazy, meaning the string is only constructed if the validation actually fails, which is a nice little performance win.

Turning Validation into Types

While require is great, it's still reactive—you're catching the error after the function is called. If you're passing a "validated" email string through five different service layers, you have to trust that every single layer remembers to call require(). I've found that the most robust way to handle this is a pattern often called "Parse, don't validate."

Instead of passing around a String and hoping it's a valid email, create a specific type for it. Kotlin's value classes are perfect for this because they give you type safety without the memory overhead of a full wrapper object. By making the constructor private and providing a factory method, you guarantee that if an instance of that class exists, it must be valid.

@JvmInline
value class Email private constructor(val value: String) {
    companion object {
        fun create(input: String): Email {
            require(input.contains("@") && input.contains(".")) { 
                "Invalid email format: $input" 
            }
            return Email(input)
        }
    }
}

// Now, your business logic doesn't need to validate the email again
fun sendWelcomeEmail(email: Email) {
    // No 'require' needed here; the type system guarantees validity
    println("Sending email to ${email.value}")
}

This shifts the burden of validation to the very edge of your application—the API controller or the UI layer. Once the data enters your core logic as an Email type, you can stop worrying about it. It’s a bit more boilerplate upfront, but it saves you from those "single whitespace" bugs that keep you up until 2 AM.




📋 Practical Task

Implementing a Validated Order System

You are building a checkout system for an e-commerce app. You need to ensure that orders cannot be created with invalid data. Your task is to implement the following validation logic:

  • Create a value class OrderId. Its constructor should be private. Provide a create factory method that ensures the ID is exactly 8 characters long and alphanumeric.
  • Create an Order data class that takes an OrderId and a quantity (Int).
  • Inside the Order init block, use require to ensure that the quantity is greater than 0 and less than or equal to 100.
  • Write a small main function that attempts to create a valid order and an invalid order (e.g., with a quantity of -5 or an OrderId of "123"), and wrap the invalid attempt in a try-catch block to print the error message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.