Skip to content

Instantly share code, notes, and snippets.

@vargasgabriel
Forked from carlosezam/LiveDataValidator.kt
Last active May 20, 2021 02:02
Show Gist options
  • Select an option

  • Save vargasgabriel/cd07e32c17d5517f856c2f536951b46c to your computer and use it in GitHub Desktop.

Select an option

Save vargasgabriel/cd07e32c17d5517f856c2f536951b46c to your computer and use it in GitHub Desktop.
Form validation with LiveData
// https://oozou.com/blog/modern-android-form-validations-with-data-binding-147
typealias Predicate<T> = (value: T?) -> Boolean
class LiveDataValidator<T>(private val liveData: LiveData<T>){
private val validationRules = mutableListOf<Predicate<T>>()
private val errorMessages = mutableListOf<String>()
var error = MutableLiveData<Message?>()
fun addRule(errorMsg: String, predicate: Predicate<T>) {
validationRules.add(predicate)
errorMessages.add(errorMsg)
}
private fun emitErrorMessage(messageRes: String?) {
error.value = messageRes
}
fun isValid(): Boolean {
for(i in 0 until validationRules.size){
if(validationRules[i](liveData.value) ){
emitErrorMessage(errorMessages[i])
return false
}
}
emitErrorMessage(null)
return true
}
}
class LiveDataValidatorResolver(private val validators: List<LiveDataValidator<*>>){
fun isValid() : Boolean = validators.all { it.isValid() }
}
val password = MutableLiveData<String>()
val passwordValidator = LiveDataValidator<String>(password).apply{
addRule("password is required") { it.isNullOrBlank() }
addRule("password length must be 7") { it?.length != 7 }
}
val isFormValid = MediatorLiveData<Boolean>().apply {
value = false
addSource(username) { value = validateForm() }
}
private fun validateForm() : Boolean {
val validators = listOf(passwordValidator)
val validatorResolver = LiveDataValidatorResolver(validators)
return validatorResolver.isValid()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment