使用 Kotlin 进行密码验证

Pop*_*ras 2 passwords validation kotlin

我是 Kotlin 新手,试图找到带条件的密码验证的最优雅的解决方案:

  1. 密码必须至少8个字符。
  2. 它必须至少有 1 个小写字母和至少 1 个大写字母。
  3. 它必须有一个特殊字符,例如!或 + 或 - 或类似的
  4. 它必须至少有 1 位数字

Art*_*ich 9

你可以这样做...

internal fun isValidPassword(password: String): Boolean {
        if (password.length < 8) return false
        if (password.filter { it.isDigit() }.firstOrNull() == null) return false
        if (password.filter { it.isLetter() }.filter { it.isUpperCase() }.firstOrNull() == null) return false
        if (password.filter { it.isLetter() }.filter { it.isLowerCase() }.firstOrNull() == null) return false
        if (password.filter { !it.isLetterOrDigit() }.firstOrNull() == null) return false

        return true
    }
Run Code Online (Sandbox Code Playgroud)


cac*_*acs 8

“优雅”是主观的!

这是一个功能性的方法:

// you can define each rule as a separate checking function,
// adding more doesn't change the complexity
fun String.isLongEnough() = length >= 8
fun String.hasEnoughDigits() = count(Char::isDigit) > 0
fun String.isMixedCase() = any(Char::isLowerCase) && any(Char::isUpperCase)
fun String.hasSpecialChar() = any { it in "!,+^" }

// you can decide which requirements need to be included (or make separate lists
// of different priority requirements, and check that enough of each have been met)
val requirements = listOf(String::isLongEnough, String::hasEnoughDigits)
val String.meetsRequirements get() = requirements.all { check -> check(this) }

fun main() {
    val password = "hiThere2!+"
    println(password.meetsRequirements)
}
Run Code Online (Sandbox Code Playgroud)

我认为这样做的好处是很容易添加新规则,并且它们可以非常简单且可读,并且您可以在单独的步骤中处理验证逻辑(例如,如果您正在实施“密码强度”指标,其中满足某些要求很重要比其他人多)。

我在那里使用了一些更高级的语言功能,但实际上是为了保持简洁。扩展String.whatever()函数只是意味着您不需要引用函数中的字符串参数(它是this),而函数引用 ( String::hasEnoughDigits) 让您可以执行该requirements.all调用而不是继续执行if (isLongEnough(password) && hasEnoughDigits(password) && ...)等等。如果你愿意的话,你可以这样做!

有很多选择和方法来实现它。正则表达式绝对可以很优雅,但它们也可能很难使用