PHP 符合 RFC 規範的 Email 驗證程式

要驗證 Email 是否符合規格, 大部分是使用下面的簡單 Regular expression 來作驗證 (下面兩者 regex 是一樣的, 只是 php / rails 版的寫法而已)

  • preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/', $email) // 正確: true, 錯誤: false
  • validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => '格式錯誤'

使用上述的檢查後, 再加上 PHP 驗證 Email -檢查 DNS 的 MX 是否有通, 再來就該直接寄信去驗證了.

在前面那段 regex 的驗證, Dominic Sayers 把 RFC 1123, 2396, 3696, 4291, 4343, 5321 & 5322 看完, 寫出下面的 PHP function, 此 function 也有附上 unit test 的測試資料, 是我看過最複雜的檢查了. XD

轉載此 Function: (Source: RFC-compliant email address validator)

描述: A PHP function that validates all parts of a given email address, according to RFCs 1123, 2396, 3696, 4291, 4343, 5321 & 5322. I’ve released it under a license that allows you to use it royalty-free in commercial or non-commercial work, subject to a few conditions. It’s almost certainly the first email address validator that correctly lets you put an IPv6 address in for the domain part.

Source

瀏覽完整版本

相關文章

最新消息

  1. 騰訊發布Hy3D 3.6生成式AI模型 強化高模結構與PBR材質 全球下載破653萬次
  2. House of Instagram盛會直擊:印度影帝沙魯克罕登台 獨家首播《KING》新曲
  3. 【CEDEC+KYUSHU 2026】製作人與編劇暢談「電馭叛客:邊緣行者」製作秘聞、跨越國界與業界障礙的衝突與協作幕後
  4. GO1選手在「SNK World Championship 2026 Finals」的餓狼傳說組別中獲勝!贏取150萬美元獎金
  5. 寶可夢30週年Special Music Video將於11月30日日本時間23時公開!歌曲為Official髭男dism的新曲「Evergreen」
  6. ROG發表搭載12顆按鍵的MMO/MOBA專用電競滑鼠「ROG Spatha X 65K」等3款新品!日本12月4日發售
  7. 寶可夢30週年最後的精選主題「延續」周邊商品登場!插畫由GAME FREAK全新繪製
  8. 「餓狼傳說CotW」新角色「麗奈」將於12月17日上線!2027年1月起Season 4開幕!