konform-kt / konform

Portable validations for Kotlin
https://www.konform.io
MIT License
652 stars 39 forks source link

Add support for custom validation #7

Closed raderio closed 5 years ago

raderio commented 5 years ago

For example we want to check that an email is unique, so we will check in database.

nlochschmidt commented 5 years ago

I haven't documented that yet, but you can create a custom validation like this:

fun ValidationBuilder<String>.uniqueEmailInDB(usersDao: UsersDao) =
    addConstraint(
        "must not exist",
    ) { email => !usersDao.exists(email) }
data class RegisterUserDTO(val email: String)

val validateRegisterUserDTO = Validation<RegisterUserDTO> {
  RegisterUserDTO::email {
    pattern("\\w+@\\w+\\.\\w+") hint "Please provide a valid email address"
    uniqueEmailInDB(usersDao) hint "Email already taken"
  }
}

However, I am curious what you are trying to use it for, because I would actually advise against checking the database in the validation. Instead I would first validate the data class against static validations and afterwards do the check against the database in the next step.

raderio commented 5 years ago

I would first validate the data class against static validations and afterwards do the check against the database

I agree, but this is also a validation, and usually you want to show that email field is bad near the input, not to show a generic/global error messages about email on top of the form.

BTW, this can be also a feature, to execute first all static validations, and only if field is valid than do the other validations

nlochschmidt commented 5 years ago

Yes, however that can just be two independent konform validations on the data class.

I am closing this ticket, since it is actually already possible to create custom validations.

raderio commented 5 years ago

Can you please add an example in README?