Just published an article on form validations and ...
# compose
n
Just published an article on form validations and state handling in Jetpack Compose. I do hope to see the support in the solution!! 🙌 https://blog.naingaungluu.me/declarative-form-validation-on-jetpack-compose-e87c0d97c802
🙌 3
c
Hi, thanks for the article! However, I'm not convinced by the problems you bring up. First, I don't like annotation validation, because it's harder to extend than regular classes. How does the user create a new validator? How can users combine validators? I read your documentation, and the boilerplate is manageable, but it's still far from native Kotlin:
Copy code
@JvmInline value class Email(val text: String) {
    init {
        require('@' in text) { "…" }
    }
}
Besides, value classes are regular types of the language, meaning they can be combined as fields of other classes etc to build complex data types.
I do agree that regular validation in Compose is a bit verbose because we can't add setter to delegated properties, but I find this much clearer:
Copy code
class FormData {
    private var _email: Email? by mutableStateOf(null)

    var email
        get() = _email
        set(value) {
             require(value.text.length < 100) { "…" }
             _email = value
        }
}
What benefits does your approach bring over this style?
By creating a small utility delegate, the previous example can be written
Copy code
class FormData {
    var email by validate(mutableStateOf<Email?>(null)) {
        require(it.text.length < 100) { "…" }
    }
}
n
Hey @CLOVIS! Thanks for taking the time to check the library and the documentation!! As for the solution, I’m aiming for the reusability and state management. You’ll notice, when using in an actual project, that it supports realtime-validation and orchestration of entire form state with just a few lines of code. Of course we could combine the states as `derivedState`s manually if we want. I love your approach on the solution too! In fact, property delegates and value classes would suffice for smaller projects perfectly. The library actually supports combined validators and custom validators.
Copy code
@Form
data class FormData(
    @EmailAddress
    @MinLength(2)
    @MaxLength(10)
    val emailAddress: String
)
The library also supports the
value
classes as Field types. And extending the existing validators is also easy as well. You’ll notice that annotations and actual validation implementations are separated as
@Annotation
and
ValidationRule
. It tries to provide those reusable APIs as building blocks for the form.
c
Thanks for your answer 🙂 I don't think I'll use the library personally, but it's great to see the ecosystem growing!
n
Sure! Whatever fits the project works right. Compose is really gaining the momentum.