Skip to content

Instantly share code, notes, and snippets.

@crisu83
Last active September 5, 2022 07:22
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 crisu83/57c586dd348083fb92848e9faacca4bb to your computer and use it in GitHub Desktop.
Save crisu83/57c586dd348083fb92848e9faacca4bb to your computer and use it in GitHub Desktop.
A validator implementation written in Kotlin.
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