Skip to content

Instantly share code, notes, and snippets.

@gildor
Created August 13, 2018 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gildor/2b2d9078253c494103e547200ecfbe59 to your computer and use it in GitHub Desktop.
Save gildor/2b2d9078253c494103e547200ecfbe59 to your computer and use it in GitHub Desktop.
Example of validation absgtraction
interface Validator {
fun validate(): Boolean
val errorMessage: String
}
abstract class EditTextValidator(
private val editText: EditText
) : Validator {
final override fun validate(): Boolean {
val isValid = isValid()
editText.isErrorEnabled = !isValid
editText.error = if (isValid) null else errorMessage
}
abstract fun isValid(): Boolean
}
class NonEmptyTextValidator(
private val editText: EditText,
fieldName: String
) : EditTextValidator(editText) {
override fun isValid() = editText.text.isNotEmpty()
override val errorMessage = "$fieldName cannot be empty."
}
class EmailValidator(private val editText: EditText) : EditTextValidator(editText) {
override fun isValid() = Patterns.EMAIL_ADDRESS.matcher(editText.text).matches()
override val errorMessage = "Email format does not valid."
}
fun main(args: Array<String>) {
val name: EditText = TODO()
val email: EditText = TODO()
val validators = listOf(
NonEmptyTextValidator(name, "Name"),
NonEmptyTextValidator(email, "Email"),
EmailValidator(email)
)
for (validator in validators) {
val result = validator.validate()
// here you can define any behavior what is good for your case:
// show all errors, or only first one
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment