Created
August 30, 2023 21:32
-
-
Save YektaDev/7bb36e7f63451ca6351867c391be6bd3 to your computer and use it in GitHub Desktop.
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
@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