Refactor: Use common password validator

Refactors password validation logic to use a common `PasswordValidator` utility. This ensures consistent password validation rules across different parts of the application, including:

- User login
- Email sign-up
- Password change
- Account removal

Also adds a string resource for password too long error message.
This commit is contained in:
2025-09-01 15:10:14 +08:00
parent 4d319351b7
commit 5c12982908
6 changed files with 159 additions and 34 deletions

View File

@@ -0,0 +1,125 @@
package com.aiosman.ravenow.utils
import android.content.Context
import com.aiosman.ravenow.R
/**
* 密码校验工具类
* 提供统一的密码校验规则和错误信息
*/
object PasswordValidator {
/**
* 密码最大长度限制
*/
const val MAX_PASSWORD_LENGTH = 64
/**
* 密码最小长度限制
*/
const val MIN_PASSWORD_LENGTH = 6
/**
* 密码校验结果
*/
data class ValidationResult(
val isValid: Boolean,
val errorMessage: String? = null
)
/**
* 校验密码格式
* @param password 密码
* @param context 上下文,用于获取本地化错误信息
* @return 校验结果
*/
fun validatePassword(password: String, context: Context): ValidationResult {
return when {
// 检查是否为空
password.isEmpty() -> ValidationResult(
false,
context.getString(R.string.text_error_password_required)
)
// 检查长度不能超过64个字符
password.length > MAX_PASSWORD_LENGTH -> ValidationResult(
false,
context.getString(R.string.text_error_password_too_long, MAX_PASSWORD_LENGTH)
)
// 检查最小长度
password.length < MIN_PASSWORD_LENGTH -> ValidationResult(
false,
context.getString(R.string.text_error_password_format)
)
// 检查是否包含至少一个数字
!password.matches(Regex(".*\\d.*")) -> ValidationResult(
false,
context.getString(R.string.text_error_password_format)
)
// 检查是否包含字母
!password.matches(Regex(".*[a-zA-Z].*")) -> ValidationResult(
false,
context.getString(R.string.text_error_password_format)
)
else -> ValidationResult(true)
}
}
/**
* 校验密码确认
* @param password 原密码
* @param confirmPassword 确认密码
* @param context 上下文
* @return 校验结果
*/
fun validatePasswordConfirmation(
password: String,
confirmPassword: String,
context: Context
): ValidationResult {
return when {
confirmPassword.isEmpty() -> ValidationResult(
false,
context.getString(R.string.text_error_confirm_password_required)
)
confirmPassword.length > MAX_PASSWORD_LENGTH -> ValidationResult(
false,
context.getString(R.string.text_error_password_too_long, MAX_PASSWORD_LENGTH)
)
password != confirmPassword -> ValidationResult(
false,
context.getString(R.string.text_error_confirm_password_mismatch)
)
else -> ValidationResult(true)
}
}
/**
* 校验当前密码(用于更改密码和删除账户场景)
* @param currentPassword 当前密码
* @param context 上下文
* @return 校验结果
*/
fun validateCurrentPassword(currentPassword: String, context: Context): ValidationResult {
return when {
currentPassword.isEmpty() -> ValidationResult(
false,
"Please enter your current password"
)
currentPassword.length > MAX_PASSWORD_LENGTH -> ValidationResult(
false,
context.getString(R.string.text_error_password_too_long, MAX_PASSWORD_LENGTH)
)
else -> ValidationResult(true)
}
}
}