函式清單
| 函式 | 用途 |
CheckMoney($val) | 驗證 99999.99 格式金額 |
CheckEmailAddr($email) | 驗證 Email 格式 |
CheckWebAddr($url) | 驗證 https:// 開頭網址 |
CheckEmpty($str) | 檢查字串非空 |
CheckLengthBetween($str, $min, $max=100) | 檢查長度區間 |
CheckUser($user) | 驗證帳號 (4-20 碼英數底線) |
CheckPassword($pwd) | 驗證密碼 (同帳號規則) |
完整程式碼
<?php
// 金額格式:數字.兩位小數
function CheckMoney($val) {
return (bool)preg_match('/^\d+\.\d{2}$/', $val);
}
// Email 格式 (簡易版)
function CheckEmailAddr($email) {
return (bool)preg_match('/^[\w\-\.]+@[\w\-]+(\.[\w\-]+)+$/', $email);
}
// 網址格式 (必須 https:// 開頭)
function CheckWebAddr($url) {
return (bool)preg_match('/^http:\/\/[\w\-]+(\.[\w\-]+)+/', $url);
}
// 非空字串
function CheckEmpty($str) {
return is_string($str) && $str !== '';
}
// 長度區間
function CheckLengthBetween($str, $min, $max = 100) {
$len = strlen(trim($str));
return $len >= $min && $len <= $max;
}
// 帳號:4-20 碼英數底線
function CheckUser($user) {
return CheckLengthBetween($user, 4, 20) && preg_match('/^[\w]+$/', $user);
}
// 密碼:同帳號規則 (實務建議加強複雜度)
function CheckPassword($pwd) {
return CheckLengthBetween($pwd, 4, 20) && preg_match('/^[\w]+$/', $pwd);
}
?>
使用範例
<?php
$tests = [
'money' => ['123.45', '123.4', 'abc'],
'email' => ['test@example.com', 'bad@', '@no'],
'url' => ['https://example.com', 'https://example.com', 'ftp://x'],
'empty' => ['', ' ', 'ok'],
'length' => ['ab', 'abcd', str_repeat('a', 101)],
'user' => ['abc', 'valid_user1', 'invalid@user'],
'pass' => ['123', 'pass1234', 'pass@word'],
];
foreach ($tests as $name => $cases) {
echo "<h3>$name</h3>";
foreach ($cases as $c) {
$fn = "Check" . ucfirst($name);
if ($name === 'length') $res = CheckLengthBetween($c, 4, 20);
else $res = $fn($c);
echo "$c => " . ($res ? '通過' : '失敗') . "<br>";
}
}
?>
進階建議
- Email 驗證建議用
filter_var($email, FILTER_VALIDATE_EMAIL) (PHP 5.2+)。
- 密碼強度應要求大小寫、數字、特殊符號,並用
password_hash() 儲存。
- 金額處理建議用
bcmath 或整數 (分) 避免浮點誤差。
- 整合至表單驗證類別,統一回傳錯誤訊息碼。