Created
October 29, 2019 17:58
-
-
Save beigirad/8f9beabc148672d58f96915c2fc3b229 to your computer and use it in GitHub Desktop.
validation method
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 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) | |
} | |
} | |
} |
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
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 */ } | |
} | |
} |
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
sealed class Validation<T> { | |
class Valid<T>(val data: T) : Validation<T>() | |
class Invalid<T>(val message: String) : Validation<T>() | |
} |
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
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