萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 表單驗證函式庫:Email、用戶名、密碼、手機、身分證、郵遞區號正則完整版

驗證函式集

<?php
declare(strict_types=1);

class Validator {
    // Email 驗證(RFC 5322 簡化版)
    public static function email(string $email): bool {
        return (bool)preg_match(
            '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',
            $email
        );
    }

    // 用戶名:字母開頭,英數底線點,4-20 字元
    public static function username(string $username): bool {
        return (bool)preg_match(
            '/^[a-zA-Z][a-zA-Z0-9._]{3,19}$/',
            $username
        );
    }

    // 密碼:英數字組合,8-20 字元,至少一字母一數字
    public static function password(string $pwd): bool {
        if (!preg_match('/^[a-zA-Z0-9]{8,20}$/', $pwd)) return false;
        if (!preg_match('/[a-zA-Z]/', $pwd)) return false;
        if (!preg_match('/\d/', $pwd)) return false;
        return true;
    }

    // 手機號(台灣制式)
    public static function phoneTW(string $phone): bool {
        return (bool)preg_match('/^09\d{8}$/', $phone);
    }

    // 手機號(中國大陸制式)
    public static function phoneCN(string $phone): bool {
        return (bool)preg_match('/^1[3-9]\d{9}$/', $phone);
    }

    // 身分證字號(台灣)
    public static function idCardTW(string $id): bool {
        if (!preg_match('/^[A-Z][12]\d{8}$/', $id)) return false;
        // 檢查碼驗證邏輯略...
        return true;
    }

    // 身分證號碼(中國大陸 18 位)
    public static function idCardCN(string $id): bool {
        return (bool)preg_match('/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/', $id);
    }

    // 郵遞區號(台灣 3+2 或 3 碼)
    public static function zipCodeTW(string $zip): bool {
        return (bool)preg_match('/^\d{3}(\d{2})?$/', $zip);
    }

    // 郵政編碼(中國大陸 6 碼)
    public static function zipCodeCN(string $zip): bool {
        return (bool)preg_match('/^[1-9]\d{5}$/', $zip);
    }
}
?>

使用範例

<?php
$inputs = [
    'email' => 'test@example.com',
    'username' => 'john_doe',
    'password' => 'Pass1234',
    'phone' => '0912345678',
];

$errors = [];
if (!Validator::email($inputs['email'])) $errors[] = 'Email 格式錯誤';
if (!Validator::username($inputs['username'])) $errors[] = '用戶名格式錯誤';
if (!Validator::password($inputs['password'])) $errors[] = '密碼需英數混合 8-20 字元';
if (!Validator::phoneTW($inputs['phone'])) $errors[] = '手機格式錯誤';

if ($errors) {
    echo implode('
', $errors); } else { echo '驗證通過'; } ?>

前端即時驗證(HTML5 + JS)

<input type="email" name="email" required
       pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
       title="請輸入有效 Email">

<input type="text" name="username" required
       pattern="[a-zA-Z][a-zA-Z0-9._]{3,19}"
       title="字母開頭,4-20 字英數底線點">

<input type="password" name="pwd" required
       pattern="(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{8,20}"
       title="英數混合 8-20 字">

正則效能優化提示

  • 編譯快取:PHP 自動快取近期正則,無需手動
  • 錨點 ^$ 讓失敗快速結束
  • 避免巢狀量詞 (a+)+ 導致災難性回溯
  • 固定字串前綴優於 .* 開頭

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved