【发布时间】:2021-12-23 22:33:19
【问题描述】:
我是 Kotlin 的新手,并试图找到最优雅的密码验证解决方案:
- 密码必须至少为 8 个字符。
- 必须至少有 1 个小写字母和至少 1 个大写字母。
- 它必须有一个特殊字符,例如!或 + 或 - 或类似
- 必须至少有 1 位数字
【问题讨论】:
标签: kotlin validation passwords
我是 Kotlin 的新手,并试图找到最优雅的密码验证解决方案:
【问题讨论】:
标签: kotlin validation passwords
“优雅”是主观的!
这是一个函数式的方法:
// 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)
}
我认为好处是添加新规则很容易,而且它们非常简单易读,并且您可以在单独的步骤中处理验证逻辑(例如,如果您正在实施“密码强度”指标,其中满足有些要求比其他要求更重要)。
我在那里使用了一些更高级的语言功能,但它确实是为了保持简洁。 String.whatever() 扩展函数只是意味着您不需要在函数中引用字符串参数(它是 this),而函数引用 (String::hasEnoughDigits) 让您可以执行 requirements.all 调用而不是去 @987654326 @ 等等。如果你愿意,你可以这样做!
有很多选择和方法来解决它。正则表达式绝对可以很优雅,但也很难使用
【讨论】:
你可以这样做......
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
}
【讨论】: