Created
December 22, 2020 00:34
-
-
Save mahdit83/927c5d8dffff25b5c19d5675092b35ea to your computer and use it in GitHub Desktop.
Field validation
This file contains 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 FieldValidator<T>(private var fieldObject: T) { | |
// Store the validation rules at a ValidationRule List, by fieldId | |
private val rules = ArrayList<Rule<T>>() | |
// Store the field error string, or null if validation pass | |
private val validations = MutableLiveData<String>() | |
// Get the LiveData<String> for the property | |
fun getValidation(): LiveData<String>? { | |
return validations | |
} | |
fun updateField(newValue: T) { | |
fieldObject = newValue | |
isValidated() | |
} | |
fun updateOtherField(newValue: T) { | |
if (fieldObject == null) return | |
rules.forEach { | |
if (it is MatchRule) { | |
it.updateOtherField(newValue) | |
} | |
} | |
} | |
fun addRule(rule: Rule<T>) { | |
rules.add(rule) | |
} | |
init { | |
isValidated() | |
} | |
@Suppress("unused") | |
fun clearAllErrors() { | |
validations.value = null | |
} | |
// Run all validations for this field, stop if we fail some rule | |
fun isValidated(): Boolean { | |
var result = true | |
rules.forEach { | |
result = result && it.validate(fieldObject) | |
if (it.validate(fieldObject).not()) { | |
validations.value = it.getErrorMessage() | |
} else if (result) { | |
validations.value = "" | |
} | |
} | |
return result | |
} | |
} | |
interface Rule<T> { | |
fun validate(t: T): Boolean | |
fun getErrorMessage(): String | |
} | |
//for example | |
data class RegexRule(val regex: Regex, val message: String) : Rule<String> { | |
override fun validate(t: String): Boolean { | |
return regex.containsMatchIn(t) | |
} | |
override fun getErrorMessage(): String = message | |
} | |
class MatchRule<T>(otherField: T, private val message: String) : Rule<T> { | |
private var otherObject: T = otherField | |
fun updateOtherField(otherField: T) { | |
this.otherObject = otherField | |
} | |
override fun validate(t: T): Boolean { | |
if (t is Int) { | |
if (t != otherObject) { | |
return false | |
} | |
} else if (t is String) { | |
if (t != otherObject) { | |
return false | |
} | |
} | |
return true | |
} | |
override fun getErrorMessage(): String = message | |
} | |
data class MaxRule(val limit: Int, val message: String) : Rule<Int> { | |
override fun validate(t: Int): Boolean { | |
if (t > limit) { | |
return false | |
} | |
return true | |
} | |
override fun getErrorMessage(): String = message | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment