-
-
Save vargasgabriel/cd07e32c17d5517f856c2f536951b46c to your computer and use it in GitHub Desktop.
Form validation with LiveData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LiveDataValidatorResolver(private val validators: List<LiveDataValidator<*>>){ | |
| fun isValid() : Boolean = validators.all { it.isValid() } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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