Skip to content

Instantly share code, notes, and snippets.

@carlosezam
Created March 30, 2021 20:42
Show Gist options
  • Select an option

  • Save carlosezam/199813107a12ae8346721de40da7538c to your computer and use it in GitHub Desktop.

Select an option

Save carlosezam/199813107a12ae8346721de40da7538c to your computer and use it in GitHub Desktop.
Form validation with LiveData
class LiveDataValidator<T>(private val liveData: LiveData<T>){
private val validationRules = mutableListOf< (T?) -> Boolean >()
private val errorMessages = mutableListOf< Message >()
var error = MutableLiveData<Message?>()
fun addRule(errorMsg: Message, predicate: (T?) -> Boolean ){
validationRules.add(predicate)
errorMessages.add(errorMsg)
}
private fun emitErrorMessage(message: Message?){
error.value = message
}
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 biometric = MutableLiveData<Agreement>()
val biometricValidator = LiveDataValidator<Agreement>( biometric ).apply{
addRule( messageOf("must acept or decline") ){ it == null }
addRule( messageOf( "must accept or devline")){ it == Agreement.Agreed }
}
val isAgreementFormValid = MediatorLiveData<Boolean>()
init {
isAgreementFormValid.value = false
isAgreementFormValid.addSource(biometric){ validateForm() }
}
fun validateForm(){
val validators = listOf( biometricValidator )
isAgreementFormValid.value = validators.all { it.isValid() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment