Skip to content

Instantly share code, notes, and snippets.

@YektaDev
Created August 30, 2023 21:32
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 YektaDev/7bb36e7f63451ca6351867c391be6bd3 to your computer and use it in GitHub Desktop.
Save YektaDev/7bb36e7f63451ca6351867c391be6bd3 to your computer and use it in GitHub Desktop.
@JvmInline
@Serializable
value class Username private constructor(@JvmField val value: String) {
companion object {
private const val MIN_LENGTH = 5
private const val MAX_LENGTH = 20
fun getOrNull(value: String): Username? = if (value.isValid()) Username(value) else null
private fun String.isValid(): Boolean {
if (length !in MIN_LENGTH..MAX_LENGTH) return false
if (this[0] == '_' || this[lastIndex] == '_' || this[0].isDigit()) return false
for (i in 0..lastIndex) {
val char = this[i]
if (!char.isDigit() && !char.isAlphabet() && char != '_') return false
if (i != lastIndex && char == '_' && this[i + 1] == '_') return false
}
return true
}
private fun Char.isAlphabet() = this in 'a'..'z' || this in 'A'..'Z'
private fun Char.isDigit() = this in '0'..'9'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment