Tips | Clean Architecture | Validation | Android
core
import android.util.Patterns
// this fun use for check if value is number
fun isNumber(value: String): Boolean {
return value.isEmpty() || Regex("^\\d+\$").matches(value)
}
fun isEmailValid(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
fun isPasswordValid(password: String): Boolean {
return password.any { it.isDigit() } &&
password.any { it.isLetter() }
}
//usecase/BaseUseCase.kt
interface BaseUseCase<In, Out> {
fun execute(input: In): Out
}
domain
//model/ValidationResult.kt
data class ValidationResult(
val successful: Boolean,
val errorMessage: UiText? = null
)
//usecase/ValidateEmailUseCase.kt
class ValidateEmailUseCase: BaseUseCase<String, ValidationResult> {
override fun execute(input: String): ValidationResult {
if (input.isBlank()) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strTheEmailCanNotBeBlank)
)
}
if (!isEmailValid(input)) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strThatsNotAValidEmail)
)
}
return ValidationResult(
successful = true,
errorMessage = null
)
}
}
//usecase/ValidatePasswordUseCase.kt
class ValidatePasswordUseCase : BaseUseCase<String, ValidationResult> {
override fun execute(input: String): ValidationResult {
if (input.length < 8) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strThePasswordNeedsToConsistOfAtLeastEightCharacters),
)
}
if (!isPasswordValid(input)) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strThePasswordNeedsToContainAtLeastOneLetterAndDigit),
)
}
return ValidationResult(
successful = true
)
}
}
//usecase/ValidatePhoneNumberUseCase.kt
class ValidatePhoneNumberUseCase : BaseUseCase<String, ValidationResult> {
override fun execute(input: String): ValidationResult {
if (input.isBlank()) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strThePhoneCanNotBeBlank),
)
}
if (!isNumber(input)) {
return ValidationResult(
successful = false,
errorMessage = UiText.StringResource(resId = R.string.strThePhoneNumberShouldBeContentJustDigit),
)
}
return ValidationResult(
successful = true,
errorMessage = null
)
}
}
//viewmodel
class MainViewModel : ViewModel() {
private val validateEmailUseCase = ValidateEmailUseCase()
private val validatePasswordUseCase = ValidatePasswordUseCase()
}