一套 PHP 表單驗證(form validation)函數,用 ereg() 正規表達式(regular expression)檢查欄位是否填妥、電郵格式,以及香港身份證(HKID)、電話號碼、出生日期的基本格式,可在正式處理用戶輸入前先過一輪驗證。
<?
function filled_out($form_vars)
{
// test that each variable has a value
foreach ($form_vars as $key => $value)
{
if (!isset($key) || ($value == ""))
// test suspended!!!!
return true;
}
return true;
}
function valid_email($address)
{
// check an email address is possibly valid
if (ereg("^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $address))
return true;
else
return false;
}
function valid_hkid($hkid_int, $hkid, $hkid_cd)
{
// check an HKID is possily valid
if ((ereg("[a-zA-Z]{1}", $hkid_int)) && (ereg("[0-9]{6}", $hkid)) && (ereg("[a-zA-Z0-9]{1}", $hkid_cd)))
return true;
else
return false;
}
function valid_phone($phone)
{
// check an HKID is valid
if (ereg("[0-9]", $phone))
return true;
else
return false;
}
function valid_bday($bday)
{
// check an HKID is valid
if (($bday < date("Y")-100) || ($bday > date("Y")-12))
return false;
else
return true;
}
?>注意:ereg() 自 PHP 5.3 起已棄用(deprecated),並於 PHP 7 移除;新項目應改用 preg_match()。
