function is_email($email) {
// 簡易版:支援常見格式,嚴格 RFC 5322 需更複雜正則
return (bool)preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/i', $email);
}
function is_user_name($user) {
// ^[a-zA-Z] 開頭為字母
// ([a-zA-Z0-9]|[._]){3,19} 後續 3-19 碼為英數或 . _
// $ 結尾
return (bool)preg_match('/^[a-zA-Z]([a-zA-Z0-9]|[._]){3,19}$/', $user);
}
function is_password($pwd) {
// \w = [a-zA-Z0-9_]
return (bool)preg_match('/^\w{4,20}$/', $pwd);
}
| 模式 | 含義 |
|---|---|
^[a-zA-Z] | 首字元必須為英文字母 |
([a-zA-Z0-9]|[._]) | 單一字元:英數字或點或底線 |
{3,19} | 重複 3 到 19 次(含首字元共 4-20 碼) |
^\w{4,20}$ | 全字串僅含 \w,長度 4-20 |
/i | Email 正則不區分大小寫 |
123456、password 等)password_hash() 儲存,驗證用 password_verify()class Validator {
public static function username($str) {
return (bool)preg_match('/^[a-zA-Z][a-zA-Z0-9._]{3,19}$/', $str);
}
public static function password($str) {
// 僅做格式檢查,強度策略另行實作
return (bool)preg_match('/^\S{8,72}$/', $str); // 非空白 8-72 碼
}
public static function email($str) {
return (bool)preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/i', $str);
}
}
// 使用
if (!Validator::username($_POST['username'])) {
exit('帳號格式錯誤:需字母開頭,4-20 碼英數底線點');
}
將驗證邏輯集中管理,便於維護與單元測試,是表單處理的專業做法。