Last active
September 5, 2022 07:22
-
-
Save crisu83/57c586dd348083fb92848e9faacca4bb to your computer and use it in GitHub Desktop.
A validator implementation written in Kotlin.
This file contains hidden or 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 interface Validator { | |
fun validate(value: String): Int? | |
} | |
object RequiredValidator : Validator { | |
override fun validate(value: String): Int? = | |
if (value.isNotBlank()) null else ValidationError.Required | |
} | |
object EmailValidator : Validator { | |
private val emailRegex = """[\w\d._%+-]+@[\w\d.-]+\.\w{2,}""".toRegex() | |
override fun validate(value: String): Int? = | |
if (emailRegex.matches(value)) null else ValidationError.InvalidEmail | |
} | |
data class LengthValidator(private val length: Int) : Validator { | |
override fun validate(value: String): Int? = | |
if (value.length >= length) null else ValidationError.TooShort | |
} | |
object NumericValidator : Validator { | |
private val numberRegex = """^-?\d+([.,]\d+)?""".toRegex() | |
override fun validate(value: String): Int? = | |
if (numberRegex.matches(value)) null else ValidationError.NotNumeric | |
} | |
@JvmInline | |
value class ValidationError private constructor(@StringRes val value: Int) { | |
companion object { | |
val Required = create(R.string.validation_required) | |
val InvalidEmail = create(R.string.validation_not_valid) | |
val TooShort = create(R.string.validation_too_short) | |
val NotNumeric = create(R.string.validation_not_numeric) | |
private fun create(@StringRes res: Int): Int { | |
return ValidationError(res).value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment