Skip to content

Instantly share code, notes, and snippets.

@beigirad
Created October 29, 2019 17:58
Show Gist options
  • Save beigirad/8f9beabc148672d58f96915c2fc3b229 to your computer and use it in GitHub Desktop.
Save beigirad/8f9beabc148672d58f96915c2fc3b229 to your computer and use it in GitHub Desktop.
validation method
class SampleValidator(
val balance: Long?,
val amount: Long?,
val acceptedTerms: Boolean?
) : Validator<SampleValidator> {
override fun validate(): Validation<SampleValidator> {
return when {
balance ?: 0 <= 0 -> Validation.Invalid("بالانس شما کافی نیست")
amount ?: 0 <= 0 -> Validation.Invalid("مبلغ وارد شده صحیح نیست")
amount ?: 0 > balance ?: 0 -> Validation.Invalid("مبلغ وارد شده بیشتر از بالانس شماست")
acceptedTerms != true -> Validation.Invalid("برای تسویه با قوانین موافقت کنید")
else -> Validation.Valid(this)
}
}
}
fun attemptForSth() {
val validator = SampleValidator(
balance = mBalanceLiveData.value?.okData?.balanceAmount,
amount = mWithdrawEnteredAmountLiveData.value?.okData,
acceptedTerms = mWithdrawAcceptedTermsLiveData.value?.okData
).validate()
return when (validator) {
is Validation.Valid -> { /* do sth */ }
is Validation.Invalid -> { /* show error */ }
}
}
sealed class Validation<T> {
class Valid<T>(val data: T) : Validation<T>()
class Invalid<T>(val message: String) : Validation<T>()
}
interface Validator<T> {
fun validate(): Validation<T>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment