摘要:[C#]老梗不死之驗證電子信箱
好幾天沒有更新blog了,原因之一是工作有點焦頭爛額,但主因還是因為寫windows phone 7的心得技術文章卡關了XDDD!
所以先來一篇轉換一下心情吧!會想寫老梗不死系列的原因是因為公司多了幾個新人,我發現新人常常在寫商業網站的時候遇到類似的問題,在google找答案,去書店翻書,屢試不爽,遙想我以前也是這樣啊!但可能就是這些問題太簡單太基本以至於很難找到資料,我把問題整理過後,把一些常用的簡單的老梗的問到爛的功能發表來跟大家分享。
第一篇就從驗證電子信箱開始吧!常常商業網站在需要客戶填寫個人基本資料時留下email,這個驗證就是預防調皮的客戶留下非正確格式之資料,當然方法很多,需要驗證的類型也很多,例如身分證驗證ˋ網域驗證ˋ手機號碼等。
像這樣的驗證,一般建議把它寫成函式,與其他驗證項目一起放在共用函數區即可。
01
public int Check_Email(string strEmail)
02
{
03
int intPos = 0, rtn_value = 0, sCnt = 0;
04
string strHost = "";
05
string strInvalidChars = "";
06
07
strEmail = strEmail.Trim();
08
09
// 1 .字串的長度是否小於 5 碼 (Email 最少要有 A@B.C,五個字所組成)
10
sCnt = strEmail.Length; // 字串長度
11
12
if (sCnt < 5)
13
{
14
rtn_value = 1;
15
}
16
17
// 2 .檢查字串中是否含有不合法的字元。
18
if (rtn_value == 0)
19
{
20
strInvalidChars = "!#$%^&*()=+{}[]|\\;:'/?>,< ";
21
22
for (intPos = 0; intPos < sCnt; intPos++)
23
{
24
if (strInvalidChars.Contains(strEmail.Substring(intPos, 1)))
25
{
26
rtn_value = 2;
27
intPos = sCnt;
28
}
29
}
30
}
31
32
// 3 檢查字串的首字或尾字是否含有"@"字元。
33
if (rtn_value == 0)
34
{
35
intPos = strEmail.IndexOf("@") + 1;
36
if (intPos == 1 || intPos == sCnt || intPos == 0)
37
rtn_value = 3;
38
}
39
40
// 4 檢查字串中含有第二個"@"字元。
41
if (rtn_value == 0)
42
{
43
// 取出郵件伺服器位址,即如一般 "hinet.net"
44
strHost = strEmail.Substring(intPos, sCnt - intPos);
45
46
if (strHost.IndexOf("@") > -1)
47
rtn_value = 4;
48
}
49
50
// 5 郵件伺服器位位址驗證。
51
if (rtn_value == 0)
52
rtn_value = Check_Host(strHost.ToLower());
53
54
return rtn_value;
55
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

就這樣,老梗不死下次再見。
|